views:

100

answers:

4

For my answer in this question I have to compare two characters. I thought that the normal char.CompareTo() method would allow me to specify a CultureInfo, but that's not the case.

So my question is: How can I compare two characters and specify a CultureInfo for the comparison?

+1  A: 

I don't think cultureInfo matters while comparing chars in C#. char is already a Unicode character so two characters can be easily compared witohut CultureInfo.

this. __curious_geek
I think the goal of the question is to have equality for different unicode characters with the same meaning in a certain culture. For instance, (when ignoring case) i and I are the same in UK, but not in Turkey.
mafutrct
I think he's looking for natural-language-porcessing kindaa tihng.
this. __curious_geek
@mafutrct, @this: Yes, I am curious which possibilities there are to compare a char within a certain culture (e.g. in turkey). There seems to be a difference, when I compare to chars and two chars casted to string.
tanascius
+1  A: 

Did you try String.Compare Method?

The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.

String.Compare(str1, str2, false, new CultureInfo("en-US"))
KMan
+2  A: 

There is no culture enabled comparison for characters, you have to convert the characters to strings so that you can use for example the String.Compare(string, string, CultureInfo, CompareOptions) method.

Example:

char a = 'å';
char b = 'ä';

// outputs -1:
Console.WriteLine(String.Compare(
  a.ToString(),
  b.ToString(),
  CultureInfo.GetCultureInfo("sv-SE"),
  CompareOptions.IgnoreCase
));

// outputs 1:
Console.WriteLine(String.Compare(
  a.ToString(),
  b.ToString(),
  CultureInfo.GetCultureInfo("en-GB"),
  CompareOptions.IgnoreCase
));
Guffa
+1  A: 

There is indeed a difference between comparing characters and strings. Let me try to explain the basic issue, which is quite simple: A character always represents a single unicode point. Comparing characters always compares the code points without any regard as to their equal meaning.

If you want to compare characters for equal meaning, you need to create a string and use the comparison methods provided there. These include support for different cultures. See Guffa's answer on how to do that.

mafutrct