A common question – Is there a way to use the String.Contains
method in C# to perform a case-insensitive match?
string title = "TEST";
title.Contains("test");
The answer is to not use the String.Contains
method, but instead use String.IndexOf
method. In C#, you can test for a case-insensitive match on a partial string using the String.IndexOf
method with the StringComparison.OrdinalIgnoreCase
option. This allows you to search for a substring within a larger string without considering differences in case.
Here’s an example of how to test for a case-insensitive match on a partial string in C#:
string str = "The quick brown fox jumps over the lazy dog.";
string substr = "BROWN";
if (str.IndexOf(substr, StringComparison.OrdinalIgnoreCase) >= 0)
{
Console.WriteLine("The substring was found (case-insensitive).");
}
else
{
Console.WriteLine("The substring was not found (case-insensitive).");
}
In this example, we define a string variable str
that contains a sentence, and a string variable substr
that contains a partial string we want to search for within str
. We then use the String.IndexOf
method to search for substr
within str
using the StringComparison.OrdinalIgnoreCase
option, which ignores differences in case.
If substr
is found within str
, the IndexOf
method will return the starting position of the first occurrence of substr
within str
. In this case, we check if the return value is greater than or equal to 0
to confirm that the substring was found. If it was found, the program will print “The substring was found (case-insensitive).” to the console. Otherwise, it will print “The substring was not found (case-insensitive).”.
It’s important to note that when using String.IndexOf
with StringComparison.OrdinalIgnoreCase
, the search is faster but less precise than using the StringComparison.CurrentCultureIgnoreCase
or StringComparison.InvariantCultureIgnoreCase
options. The StringComparison.CurrentCultureIgnoreCase
option uses the culture-specific rules for case-insensitive comparisons, while the StringComparison.InvariantCultureIgnoreCase
option uses a culture-independent comparison that is more consistent across different cultures.