Sakthivel
Sakthivel

Reputation: 1938

Which Cultural information is used in string comparison?

I got a hint from my TL, that i should not use just string.compare since i am working with programmatic strings. what he actually wanted to say ? do we have any cultural information on strings ? and what is the benefit of using stringComparision.Ordinal ?

Upvotes: 2

Views: 76

Answers (2)

Guffa
Guffa

Reputation: 700362

If you don't specify any comparison options, the String.Compare method will make a culture dependant comparison using the current culture setting by default. This means that the characters are compared using the sort order for that specific culture.

If you specify the Ordinal comparison, the characters are compared only based on their Unicode character code.

One benefit of using the ordinal comparison is that it's faster. This would matter if you are going to do a lot of comparisons.

An example where the result of the comparison differs:

Console.WriteLine(String.Compare("å", "ä"));
Console.WriteLine(String.Compare("å", "ä", StringComparison.Ordinal));

Output:

-1
1

Upvotes: 2

Bogdan Gavril MSFT
Bogdan Gavril MSFT

Reputation: 21458

String comparison will use the current culture, i.e. the one the Operating System has (you can change it if you go to Region settings in Windows)

This is from msdn:

The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters

If you don't want culture to be an issue, you can always specify comparison like this:

String.Compare("a", "a", StringComparison.InvariantCulture);

Upvotes: 1

Related Questions