Find a substring in a case-insensitive way - C#
You can use the IndexOf() method, which takes in a StringComparison type:
string s = "foobarbaz";
int index = s.IndexOf("BAR", StringComparison.CurrentCultureIgnoreCase); // index = 3
If the string was not found, IndexOf() returns -1.
There's no case insensitive version. Use IndexOf
instead (or a regex though that is not recommended and overkill).
string string1 = "my string";
string string2 = "string";
bool isContained = string1.IndexOf(string2, StringComparison.OrdinalIgnoreCase) >= 0;
StringComparison.OrdinalIgnoreCase
is generally used for more "programmatic" text like paths or constants that you might have generated and is the fastest means of string comparison. For text strings that are linguistic use StringComparison.CurrentCultureIgnoreCase
or StringComparison.InvariantCultureIgnoreCase
.
Contains returns a boolean if a match is found. If you want to search case-insensitive, you can make the source string and the string to match both upper case or lower case before matching.
Example:
if(sourceString.ToUpper().Contains(stringToFind.ToUpper()))
{
// string is found
}