46

Possible Duplicate:
Case insensitive contains(string)

With Contains() method of String class a substring can be found. How to find a substring in a string in a case-insensitive manner?

Community
  • 1
  • 1
Falcon
  • 507
  • 1
  • 4
  • 7

5 Answers5

75

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.

Marty
  • 7,464
  • 1
  • 31
  • 52
15

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.

plr108
  • 1,201
  • 11
  • 16
scottheckel
  • 9,106
  • 1
  • 35
  • 47
  • If you run the measure-command speed of this vs the OrdinalIgnoreCase option the toupper()/tolower().. converting all strings to lower case and then doing a standard indexof() w/out ordinalignorecase, the tolower() version is about 25% faster on both big and small strings. – danekan May 15 '19 at 23:32
  • But takes more memory, as the ToLower/ToUpper needs to allocate memory for new strings. Granted, everything needs to be taken into account. – Ricardo Peres Feb 07 '20 at 09:27
6

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
}
Jesse van Assen
  • 2,240
  • 2
  • 16
  • 19
  • This generates two additional strings, one for each ToUpper, which results in more memory usage. Best way is to use the IndexOf overload that takes a comparer. – Ricardo Peres Feb 07 '20 at 09:27
2

stringToSearch.ToLower().Contains(stringToSearchFor.ToLower())

Esoteric Screen Name
  • 6,082
  • 4
  • 29
  • 38
  • This generates two additional strings, one for each ToLower, which results in more memory usage. Best way is to use the IndexOf overload that takes a comparer. – Ricardo Peres Feb 07 '20 at 09:25
1
string myString = "someTextorMaybeNot";
myString.ToUpper().Contains( "text".ToUpper() );
Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
  • This generates two additional strings, one for each ToUpper, which results in more memory usage. Best way is to use the IndexOf overload that takes a comparer. – Ricardo Peres Feb 07 '20 at 09:25