Ignore case with string.Contains() in C#
By FoxLearn 2/5/2025 8:51:57 AM 63
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#