Ignoring accented letters in string comparison

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

    I had to do something similar but with a StartsWith method. Here is a simple solution derived from @Serge - appTranslator.

    Here is an extension method:

        public static bool StartsWith(this string str, string value, CultureInfo culture, CompareOptions options)
        {
            if (str.Length >= value.Length)
                return string.Compare(str.Substring(0, value.Length), value, culture, options) == 0;
            else
                return false;            
        }
    

    And for one liners freaks ;)

        public static bool StartsWith(this string str, string value, CultureInfo culture, CompareOptions options)
        {
            return str.Length >= value.Length && string.Compare(str.Substring(0, value.Length), value, culture, options) == 0;
        }
    

    Accent incensitive and case incensitive startsWith can be called like this

    value.ToString().StartsWith(str, CultureInfo.InvariantCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)
    

提交回复
热议问题