Ignore case with string.Contains() in C#
By Tan Lee Published on Feb 05, 2025 426
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
Structured Data using FoxLearn.JsonLd
Jun 20, 2025
Implement security headers for an ASP.NET Core
Jun 24, 2025
10 Common Mistakes ASP.NET Developers Should Avoid
Dec 16, 2024
HTML Bootstrap 4 Login, Register & Reset Template
Nov 11, 2024