How to make String.Contains case insensitive?

January 04, 2014 by Anuraj

.Net .Net 3.0 / 3.5 .Net 4.0 ASP.Net Windows Forms

The string.Contains() method in C# is case sensitive. And there is not StringComparison parameter available similar to Equals() method, which helps to compare case insensitive.

If you run the following tests, TestStringContains2() will fail.

[TestMethod]
public void TestStringContains()
{
    var text = "This is a sample string";
    Assert.IsTrue(text.Contains("sample"));
}

[TestMethod]
public void TestStringContains2()
{
    var text = "This is a sample string";
    Assert.IsTrue(text.Contains("Sample"));
}

Unit Tests - string.Contains method

Other option is using like this.

Assert.IsTrue(text.ToUpper().Contains("Sample".ToUpper()));

And here is the case insensitive contains method implementation.

public static class Extensions
{
    public static bool CaseInsensitiveContains(this string text, string value, 
        StringComparison stringComparison = StringComparison.CurrentCultureIgnoreCase)
    {
        return text.IndexOf(value, stringComparison) >= 0;
    }
}

And here is the modified tests.

[TestMethod]
public void TestStringContains()
{
    var text = "This is a sample string";
    Assert.IsTrue(text.CaseInsensitiveContains("sample"));
}

[TestMethod]
public void TestStringContains2()
{
    var text = "This is a sample string";
    Assert.IsTrue(text.CaseInsensitiveContains("Sample"));
}

And here is the tests running

Modified unit tests

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub