Ignore case with string.Contains() in C#
By FoxLearn 2/5/2025 8:51:57 AM 40
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.
- Primitive types in C#
- Connection string password with special characters in C#
- Ignoring Namespaces in XML when Deserializing in C#
- How to Change the Cursor to a Wait Cursor in C#
- Enum Generic Type Constraint in C#
- Capturing screenshots in C#
- ChromeDevToolsSystemMenu does not exist in the current context in CefSharp
- How to download a webfile in C#
Categories
Popular Posts
Material Admin Dashboard Template
11/15/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024
SB Admin Template
11/17/2024