Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem comparing French character Î

When comparing "Île" and "Ile", C# does not consider these to be to be the same.

    string.Equals("Île", "Ile", StringComparison.InvariantCultureIgnoreCase)

For all other accented characters I have come across the comparison works fine.

Is there another comparison function I should use?

like image 979
Bryan Avatar asked May 20 '10 17:05

Bryan


1 Answers

You are specifying to compare the strings using the Invariant culture's comparison rules. Evidently, in the invariant culture, the two strings are not considered equal.

You can compare them in a culture-specific manner using String.Compare and providing the culture for which you want to compare the strings:

if(String.Compare("Île", "Ile", new CultureInfo("fr-FR"), CompareOptions.None)==0)

Please note that in the french culture, those strings are also considered different. I included the example to show, that it is the culture that defines the sort rules. You might be able to find a culture that fits your requirements, or build a custom one with the needed compare rules, but that it probably not what you want.

For a good example of normalizing the string so there are no accents, have a look at this question. After normalizing the string, you would be able to compare them and consider them equal. This would probably be the easiest way to implement your requirement.

Edit

It is not just the I character that has this behaviour in the InvariantCulture, this statement also returns false:

String.Equals("Ilê", "Ile", StringComparison.InvariantCultureIgnoreCase)

The framework does the right thing - those characters are in fact different (has different meaning) in most cultures, and therefore they should not be considered the same.

like image 179
driis Avatar answered Oct 19 '22 09:10

driis