How to compare characters (respecting a culture)

℡╲_俬逩灬. 提交于 2020-01-14 08:59:07

问题


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:


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.




回答2:


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
));



回答3:


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"))



回答4:


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.



来源:https://stackoverflow.com/questions/2880784/how-to-compare-characters-respecting-a-culture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!