Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two strings, ignoring case in C# [duplicate]

Which of the following two is more efficient? (Or maybe is there a third option that's better still?)

string val = "AStringValue";  if (val.Equals("astringvalue", StringComparison.InvariantCultureIgnoreCase)) 

OR

if (val.ToLowerCase() == "astringvalue") 

?

like image 906
pwmusic Avatar asked Jun 16 '11 11:06

pwmusic


People also ask

Which method is used to compare two strings ignoring the case C?

The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

How do you compare two string cases insensitive?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function. Example 1: This example uses toUpperCase() function to compare two strings.

Which library function compare two strings by ignoring the case?

The strcasecmp() function compares, while ignoring differences in case, the string pointed to by string1 to the string pointed to by string2.

How do you compare the first n characters of two strings by ignoring the case?

tf = strncmpi( s1,s2 , n ) compares up to n characters of s1 and s2 , ignoring any differences in letter case. The function returns 1 ( true ) if the two are identical and 0 ( false ) otherwise.


2 Answers

If you're looking for efficiency, use this:

string.Equals(val, "astringvalue", StringComparison.OrdinalIgnoreCase) 

Ordinal comparisons can be significantly faster than culture-aware comparisons.

ToLowerCase can be the better option if you're doing a lot of comparisons against the same string, however.

As with any performance optimization: measure it, then decide!

like image 62
Sven Avatar answered Oct 04 '22 06:10

Sven


The first one is the correct one, and IMHO the more efficient one, since the second 'solution' instantiates a new string instance.

like image 22
Frederik Gheysels Avatar answered Oct 04 '22 06:10

Frederik Gheysels