比较字符串与几个不同的字符串

我想比较一个字符串和许多字符串。 如何在C#中完成?

如果要检查字符串列表中是否Contains字符串,可以使用Contains扩展方法:

 bool isStringContainedInList = new[] { "string1", "string2", "string3" }.Contains("some string") 

我建议您查看这篇维基百科文章,了解最常见的子字符串问题

我从本科生那里回忆起找到最长公共子串的一种策略,你可以从找到一个稍短的子串开始,然后从那里扩展(并重复)。 也就是说,如果“abcd”是一个公共子串,那么“abc”也是如此,“ab”也是如此。

这有助于重复算法,您首先找到字符串中出现的所有2个字母对(我不打扰一个字母子字符串,因为对于大型数据集,它们将包括整个字母表)。 然后你再次迭代找到所有3个字母的子串,依此类推……

要将集合中的所有字符串相互比较以查找重复项,使用Dictionary最有效:

 string[] strings = { "Zaphod", "Trillian", "Zaphod", "Ford", "Arthur" }; var count = new Dictionary(); foreach (string s in strings) { if (count.ContainsKey(s)) { count[s]++; } else { count.Add(s, 1); } } foreach (var item in count) { Console.WriteLine("{0} : {1}", item.Key, item.Value); } 

输出:

 Zaphod : 2 Trillian : 1 Ford : 1 Arthur : 1 

您也可以使用LINQ方法执行此操作:

 var count = strings .GroupBy(s => s) .Select( g => new { Key = g.First(), Value = g.Count() } ); 
  string[] comparisonList = {"a", "b" "c"}; from s in comparisonList where comparisonList.Contains("b") select s; 

如果要进行比较,请使用String.Compare 。
如果要在列表中查找字符串,请使用与列表类型等效的Contains / Select方法。

我喜欢使用String.Compare()静态方法,因为它让你明确一切。 这很重要,因为字符串比较可能因微妙的错误而臭名昭着。

例如:

 // Populate with your strings List manyStrings = new List(); string oneString="target string"; foreach(string current in manyStrings) { // For a culture aware, safe comparison int compareResult=String.Compare(current,oneString, StringComparison.CurrentCulture); // OR // For a higher performance comparison int compareResult=String.Compare(current,oneString, StringComparison.Ordinal); if (compareResult==0) { // Strings are equal } } 

如果你真的想知道一个字符串是否是另一个更大字符串的子字符串,在上面的循环中你可以使用:

 int indexPos=current.IndexOf(oneString,StringComparison.Ordinal); if (indexPos>=0) { // oneString was found in current } 

请注意,IndexOf接受相同的有用StringComparison枚举。

要在列表中查找列表中多次出现的字符串,您可以开始将这些字符串放入HashSet中,并检查每个字符串是否已存在于此集合中。

例如,您可以:

 HashSet hashSet = new HashSet(); foreach (string item in myList) { if (hashSet.Contains(item)) { // already in the list ... } else { // not seen yet, putting it into the hash set hashSet.Add(item); } }