Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caselessly comparing strings in C#

Let's say I have two strings: a and b. To compare whether a and be have the same values when case is ignored, I've always used:

// (Assume a and b have been verified not to be null)

if (a.ToLower() == b.ToLower())

However, using Reflector, I've seen this a few times in the .NET Framework:

// (arg three is ignoreCase)

if (string.Compare(a, b, true) == 0)

I tested which is faster, and the ToLower() beat Compare() every time with the strings I used.

Is there a reason why to Compare() instead of ToLower()? Something about different CultureInfo? I'm scratching my head.

like image 425
core Avatar asked Feb 02 '09 00:02

core


People also ask

How do you compare two strings in C?

We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.

Can you use == when comparing strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

Can you compare strings with == in C?

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

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


1 Answers

The main thing you should be concerned about isn't performance, it's correctness, and from that aspect the method you probably want to be using for a case insensitive comparison is either:

string.Compare(a, b, StringComparison.OrdinalIgnoreCase) == 0;

or

a.Equals(b, StringComparison.OrdinalIgnoreCase)

(The first one is useful if you know the strings may be null; the latter is simpler to write if you already know that at least one string is non-null. I've never tested the performance but assume it will be similar.)

Ordinal or OrdinalIgnoreCase are a safe bet unless you know you want to use another comparison method; to get the information needed to make the decision read this article on MSDN.

like image 94
Greg Beech Avatar answered Sep 30 '22 04:09

Greg Beech