Insensitive StringA.Contains(StringB)?

This question already has an answer here:

  • Case insensitive 'Contains(string)' 22 answers
  • Case Insensitive comparison in C# [duplicate] 7 answers

  • You can convert both strings to upper case before performing the check:

    string1.ToUpperInvariant().Contains(string2.ToUpperInvariant())
    

    Or if you want to take the current culture into account when defining case insesitivity:

    string1.ToUpper().Contains(string2.ToUpper())
    

    Or you could even use a specific culture by calling the ToUpper overload that accepts a CultureInfo .

    The reason that you should convert to upper case and not lower case is described in code analysis warning CA1308: Normalize strings to uppercase:

    Strings should be normalized to uppercase. A small group of characters, when they are converted to lowercase, cannot make a round trip. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters.

    You may wonder what "small group of characters" are affected by this and apparently at least some Georgian scripts have this problem according to Michael S. Kaplan.


    使用String.IndexOf方法(String,StringComparison)

    string str = "Some test String";
    string str2 = "test";
    if (str.IndexOf(str2, StringComparison.InvariantCultureIgnoreCase) > 0)
    {
        //str contains str2
    }
    else
    {
        //str does not contain str2
    }
    

    string1.ToUpper().Contains(string2.ToUpper())
    
    链接地址: http://www.djcxy.com/p/13086.html

    上一篇: C#不区分大小写的字符串比较

    下一篇: 不敏感的StringA.Contains(StringB)?