How to make String.Contains case insensitive?
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"));
}
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
Happy Programming :)