How to compare strings with case insensitive and without accents

How to compare strings with case insensitive and without accent

Good thing this is easily done on SQL Server

However, I would like to do the same in C # .NET 4.5.1.

How can I do this in the best way?

I mean, these 3 lines should return equal when comparing

http://www.buroteknik.com/metylan-c387c4b0ft-tarafli-bant-12cm-x25mt_154202.html http://www.buroteknik.com/METYLAN-C387C4B0FT-TARAFLI-BANT-12cm-x25mt_154202.html http://www.buroteknik.com/METYLAN-C387C4B0FT-TARAFLı-BANT-12cm-x25mt_154202.html 

I need a method that would say that the 2 below are similar to the same SQL server that they are equal.

  tarafli TARAFLİ 
+7
c # case-insensitive string-comparison accent-insensitive
source share
2 answers

To ignore both case and arguments, you can use string.Compare() with IgnoreNonSpace and IgnoreCase , for example:

 string s1 = "http://www.buroteknik.com/metylan-c387c4b0ft-tarafli-bant-12cm-x25mt_154202.html"; string s2 = "http://www.buroteknik.com/METYLAN-C387C4B0FT-TARAFLI-BANT-12cm-x25mt_154202.html"; string s3 = "http://www.buroteknik.com/METYLAN-C387C4B0FT-TARAFLı-BANT-12cm-x25mt_154202.html"; Console.WriteLine(string.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)); Console.WriteLine(string.Compare(s2, s3, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)); 

In response to your comments below, this works for tarafli and TARAFLİ .

The following code prints 0, meaning the lines are equal :

 string s1 = "tarafli"; string s2 = "TARAFLİ"; Console.WriteLine(string.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)); 

And here he uses Turkish culture (I guess what the right culture is). This also prints 0:

 string s1 = "tarafli"; string s2 = "TARAFLİ"; var trlocale = CultureInfo.GetCultureInfo("tr-TR"); Console.WriteLine(string.Compare(s1, s2, trlocale, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)); 
+11
source share

You can use string.Compare with an overload that accepts the correct CultureInfo and CompareOptions :

 string.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase); 

Edit:

Regarding your question about CultureInfo , from MSDN :

The comparison uses a culture parameter to obtain culture-specific information, such as casing rules and alphabetical order of individual characters. For example, a particular culture may indicate that certain combinations of characters are treated as a single character, so that upper and lower case characters are compared in a special way, or that the character's sort order depends on the characters that precede or follow it.

+3
source share

All Articles