Ignore case with string.Contains() in C#
By Tan Lee Published on Feb 05, 2025 172
By default, string.Contains() performs a case-sensitive search for a substring (or character) within a string.
To make it case-insensitive, you can use StringComparison.OrdinalIgnoreCase
.
For example:
string sentence = "The quick Brown fox jumps over the lazy Dog."; if (sentence.Contains("brown", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine($"'{sentence}' contains 'brown'"); }
Output:
'The quick Brown fox jumps over the lazy Dog.' contains 'brown'
This works because it's performing a case-insensitive search, and it matches "brown" with "Brown" in the sentence.
Use string.IndexOf() with StringComparison
If you are working with an older version of .NET that doesn't support the string.Contains()
overload with StringComparison
, you can use string.IndexOf()
instead, which works similarly.
string sentence = "The quick Brown fox jumps over the lazy Dog."; int index = sentence.IndexOf("brown", StringComparison.OrdinalIgnoreCase); if (index > -1) { Console.WriteLine($"'{sentence}' contains 'brown', starting at index {index}"); }
Output:
'The quick Brown fox jumps over the lazy Dog.' contains 'brown', starting at index 10
In this case, it finds "brown" starting at index 10 in the string. This is how string.Contains()
works internally, but with IndexOf()
, you also get the starting position of the substring.
Categories
Popular Posts
Portal HTML Bootstrap
Nov 13, 2024
Freedash bootstrap lite
Nov 13, 2024
Implementing Caching in ASP.NET Core
Dec 14, 2024
11 Things You Didn't Know About Cloudflare
Dec 19, 2024