How can I test whether a substring is contained in other, but case-insensitively?
string1.Contains(string2) is not case insensitive. if there is no existing method, I would want to write a optimized method, any pointer for that?
Edit: It should also work with globalization.
5 Answers 5
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.
6 Comments
ToUpperInvariant converts to upper case using the invariant culture (CultureInfo.InvariantCulture) which is based on the "en-US" culture. Upper casing the letter i will result in I. Using ToUpper(CultureInfo.GetCultureInfo("tr-TR")) will result in İ (Turkish upper case dotted I) as pointed out by Soner Gönül.Use String.IndexOf Method (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
}
Comments
string1.ToUpper().Contains(string2.ToUpper())
2 Comments
You can use this overload of String.IndexOf Method (String, StringComparison)
For StringComparison.InvariantCultureIgnoreCase
Compare strings using culture-sensitive sort rules, the invariant culture, and ignoring the case of the strings being compared.
string string1 = "YOURSTRING";
bool containsornot = string1 .IndexOf("yourstring", StringComparison.InvariantCultureIgnoreCase) >= 0;
Here is a DEMO.
Comments
have you tried string1.IndexOf(string2, StringComparison.InvariantCultureIgnoreCase)
or use StringComparison.OrdinalIgnoreCase
3 Comments
StringComparison.OrdinalIgnoreCase