Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to compare a string with an array of strings in C#2.0

What is the fastest way to compare a string with an array of strings in C#2.0

like image 595
Greens Avatar asked Jun 26 '09 21:06

Greens


People also ask

Is strcmp faster than ==?

While comparing the two function, in a loop repeted 500'000'000 times, strcmp execute too much fast, about x750 times faster. The execution time of that function is 3.058s , while strcmp only 0.004s .

Can we compare string with array?

You can compare and sort string arrays with relational operators, just as you can with numeric arrays. Use == to determine which elements of two string arrays are equal.

How do you compare two strings in an array?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

Can you compare C strings with ==?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.


1 Answers

What kind of comparison do you want? Do you want to know if the given string is in the array?

bool targetStringInArray = array.Contains(targetString);

do you want an array of comparison values (positive, negative, zero)?

var comparisons = array.Select(x => targetString.CompareTo(x));

If you're checking for containment (i.e. the first option) and you're going to do this with multiple strings, it would probably be better to build a HashSet<string> from the array:

var stringSet = new HashSet<string>(array);

if (stringSet.Contains(firstString))  ...
if (stringSet.Contains(secondString)) ...
if (stringSet.Contains(thirdString))  ...
if (stringSet.Contains(fourthString)) ...
like image 135
Jon Skeet Avatar answered Oct 01 '22 11:10

Jon Skeet