Comparing a string with several different strings

I want to compare one line with many lines. How is this done in C #?

+3
source share
7 answers

If you want to check if a string is in the string list, you can use the extension method Contains:

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

I recommend that you read this article about the longest common substring problem .

undergrad, , , ( ). , "abcd" , "abc", "ab".

, , ( , ). , 3- ...

+6

, , , :

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

:

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

LINQ:

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

, String.Compare.
, Contains/Select, .

0

String.Compare(), . , .

:

// 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 

    }
}

, , :

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

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

, IndexOf StringComparison.

0

To find the lines in the list that are in the list several times, you can start placing these lines in the HashSet and checking each of them, regardless of whether it is already in this set.

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

Source: https://habr.com/ru/post/1728573/


All Articles