What is the correct way to compare char ignoring case?

前端 未结 9 2469
不知归路
不知归路 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:14

    I would recommend comparing uppercase, and if they don't match then comparing lowercase, just in case the locale's uppercasing and lowercasing logic behave slightly different.

    Addendum

    For example,

    int CompareChar(char c1, char c2)
    {
        int  dif;
    
        dif = char.ToUpper(c1) - char.ToUpper(c2);
        if (diff != 0)
            dif = char.ToLower(c1) - char.ToLower(c2);
        return dif;
    }
    

提交回复
热议问题