C# – Ignore case with string.Contains()

By default, string.Contains() does a case sensitive search for a substring (or character) in a string. You can make it do a case insensitive search instead by passing in StringComparison.OrdinalIgnoreCase, like this:

string input = "Welcome to Earth!";

if (input.Contains("earth", StringComparison.OrdinalIgnoreCase))
{
    Console.WriteLine($"'{input}' contains 'earth'");
}
Code language: C# (cs)

Note: StringComparison has three ‘ignore case’ options to choose from.

Because this is doing a case insensitive search, it matched “earth” to “Earth” and returns true. This outputs the following:

'Welcome to Earth!' contains 'earth'Code language: plaintext (plaintext)

Use string.IndexOf() with StringComparison

The string.Contains() overload with StringComparison was added in .NET Core 2.1. If you’re using an older version that doesn’t have this overload, you can use string.IndexOf() with StringComparison instead. In fact, this is exactly what string.Contains() uses.

string.IndexOf() returns -1 if the substring wasn’t found. So here’s how you can use this to check if a string contains a substring:

string input = "Welcome to Earth!";

int index = input.IndexOf("earth", StringComparison.OrdinalIgnoreCase);

if (index > -1)
{
    Console.WriteLine($"'{input}' contains 'earth', starting at index {index}");
}
Code language: C# (cs)

It found “earth” starting at index 11, so this outputs the following:

'Welcome to Earth!' contains 'earth', starting at index 11Code language: plaintext (plaintext)

Leave a Comment