Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare characters (respecting a culture)

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?

like image 615
tanascius Avatar asked May 21 '10 09:05

tanascius


People also ask

How do you compare characters in a string?

String comparison by Using String Library Functionstrcmp() function is used to compare two strings. The strcmp() function takes two strings as input and returns an integer result that can be zero, positive, or negative. The strcmp() function compares both strings characters.

Which is the string method used to compare two strings with each other in C#?

The C# Compare() method is used to compare first string with second string lexicographically. It returns an integer value. If both strings are equal, it returns 0.


1 Answers

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
));
like image 195
Guffa Avatar answered Sep 17 '22 20:09

Guffa