Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a substring in a case-insensitive way - C# [duplicate]

Tags:

c#

.net

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?

like image 877
Falcon Avatar asked Dec 13 '11 19:12

Falcon


People also ask

Is Strstr case-sensitive in C?

It's a cousin to the standard C library string comparison function, strstr(). The word case sandwiched inside means that the strings are compared in a case-insensitive way. Otherwise, both functions are identical.

How do you check if a string contains another string in a case-insensitive manner in Python?

Ignore case : check if a string exists in another string in case insensitive approach. Use re.search() to find the existence of a sub-string in the main string by ignoring case i.e. else return a tuple of False & empty string.

How do you do case-insensitive string comparison?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function.


2 Answers

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.

like image 64
Marty Avatar answered Sep 22 '22 06:09

Marty


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.

like image 45
scottheckel Avatar answered Sep 23 '22 06:09

scottheckel