Find a substring in a case

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?


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 index of instead (or a regex).

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
}
链接地址: http://www.djcxy.com/p/13082.html

上一篇: 在C#中不区分大小写的比较

下一篇: 在案例中查找一个子字符串