Ignoring accented letters in string comparison

后端 未结 6 1146
一向
一向 2020-11-22 10:37

I need to compare 2 strings in C# and treat accented letters the same as non-accented letters. For example:

string s1 = \"hello\";
string s2 = \"héllo\";

s1         


        
6条回答
  •  无人及你
    2020-11-22 11:07

    If you don't need to convert the string and you just want to check for equality you can use

    string s1 = "hello";
    string s2 = "héllo";
    
    if (String.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) == 0)
    {
        // both strings are equal
    }
    

    or if you want the comparison to be case insensitive as well

    string s1 = "HEllO";
    string s2 = "héLLo";
    
    if (String.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) == 0)
    {
        // both strings are equal
    }
    

提交回复
热议问题