C# 将一个字符串与几个不同的字符串进行比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2070013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:14:13  来源:igfitidea点击:

Comparing a string with several different strings

c#algorithmstring

提问by user251334

I want to compare one string with many strings. How is that done in C#?

我想将一个字符串与多个字符串进行比较。在 C# 中是如何完成的?

回答by Darin Dimitrov

If you want to check if a string is contained in a list of strings you could use the Containsextension method:

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

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

回答by Esteban Araya

 string[] comparisonList = {"a", "b" "c"};
 from s in comparisonList where comparisonList.Contains("b") select s;

回答by Gishu

If you want to compare, use String.Compare.
If you to find a string in a list, use the Contains/Select method equivalent of the list type.

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

回答by Ash

I like to use the String.Compare()static method as it let's you make everything explicit. This is important as string comparisons can be notorious for subtle bugs.

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

For example:

例如:

// Populate with your strings
List<string> manyStrings = new List<string>();

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 

    }
}

If you actually want to just know if a string is a substring of another larger string, in the above loop you can use:

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

int indexPos=current.IndexOf(oneString,StringComparison.Ordinal); 

if (indexPos>=0)
{
    // oneString was found in current
}

Note that IndexOf accepts the same useful StringComparison enumeration.

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

回答by treaschf

To find the strings in your list, which are in the list for multiple times, you could start putting those strings into a HashSet, and check for each one, whether it is already in this set.

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

For example, you could:

例如,您可以:

HashSet<string> hashSet = new HashSet<string>();

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);
    }
}

回答by Yoni

I recommend that you look at this wikipedia articleabout the longest common substring problem.

我建议您查看这篇关于最长公共子串问题的维基百科文章

I recall from undergrad that one strategy to find the longest common substring, you can start by finding a slightly shorter substring and then expand from there (and repeat). That is, if "abcd" is a common substring, then so does "abc" and so does "ab".

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

This lends to a repeating algorithm where you first find all the 2-letters pairs that appear in your strings (I am not bothering with one letter substrings because for large dataset they'll get include the whole alphabet). Then you iterate again to find all 3-letters substrings, and so on ...

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

回答by Guffa

To compare all strings in a collection to each other to find duplicates, it's most efficient to use a Dictionary:

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

string[] strings = { "Zaphod", "Trillian", "Zaphod", "Ford", "Arthur" };

var count = new Dictionary<string, int>();
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);
}

Output:

输出:

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

You can also do it using LINQ methods:

您也可以使用 LINQ 方法来做到这一点:

var count =
  strings
  .GroupBy(s => s)
  .Select(
    g => new { Key = g.First(), Value = g.Count() }
  );