How to make String.Contains case insensitive?

Posted by Anuraj on Saturday, January 4, 2014

.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 :)



Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



Subscribe


Copyright © 2017 - Anuraj P. 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. Hosted with ❤ by GitHub