What is the correct way to compare char ignoring case?

前端 未结 9 2490
不知归路
不知归路 2020-12-01 20:31

I\'m wondering what the correct way to compare two characters ignoring case that will work for all cultures. Also, is Comparer.Default the best way

9条回答
  •  再見小時候
    2020-12-01 21:09

    It depends on what you mean by "work for all cultures". Would you want "i" and "I" to be equal even in Turkey?

    You could use:

    bool equal = char.ToUpperInvariant(x) == char.ToUpperInvariant(y);
    

    ... but I'm not sure whether that "works" according to all cultures by your understanding of "works".

    Of course you could convert both characters to strings and then perform whatever comparison you want on the strings. Somewhat less efficient, but it does give you all the range of comparisons available in the framework:

    bool equal = x.ToString().Equals(y.ToString(), 
                                     StringComparison.InvariantCultureIgnoreCase);
    

    For surrogate pairs, a Comparer isn't going to be feasible anyway, because you don't have a single char. You could create a Comparer though.

提交回复
热议问题