Ignoring accented letters in string comparison

后端 未结 6 1212
一向
一向 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:04

    try this overload on the String.Compare Method.

    String.Compare Method (String, String, Boolean, CultureInfo)

    It produces a int value based on the compare operations including cultureinfo. the example in the page compares "Change" in en-US and en-CZ. CH in en-CZ is a single "letter".

    example from the link

    using System;
    using System.Globalization;
    
    class Sample {
        public static void Main() {
        String str1 = "change";
        String str2 = "dollar";
        String relation = null;
    
        relation = symbol( String.Compare(str1, str2, false, new CultureInfo("en-US")) );
        Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2);
    
        relation = symbol( String.Compare(str1, str2, false, new CultureInfo("cs-CZ")) );
        Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2);
        }
    
        private static String symbol(int r) {
        String s = "=";
        if      (r < 0) s = "<";
        else if (r > 0) s = ">";
        return s;
        }
    }
    /*
    This example produces the following results.
    For en-US: change < dollar
    For cs-CZ: change > dollar
    */
    

    therefor for accented languages you will need to get the culture then test the strings based on that.

    http://msdn.microsoft.com/en-us/library/hyxc48dt.aspx

提交回复
热议问题