Case Insensitive Contains String Function in C#
-
Create a Case-Insensitive
Contains
Function UsingString.IndexOf
WithStringComparison.OrdinalIgnoreCase
in C# -
Create a Case-Insensitive
Contains
Function UsingCultureInfo.CompareInfo.IndexOf
WithCompareOptions.IgnoreCase
in C# -
Create a Case-Insensitive
Contains
Function UsingString.Contains
WithStringComparison.OrdinalIgnoreCase
in C# -
Create a Case-Insensitive
Contains
Function UsingString.Contains
WithStringComparison.OrdinalIgnoreCase
in C# - Conclusion
Case-insensitive searching is a common requirement when dealing with string manipulations. In C#, the Contains
method provided by the String
class is case-sensitive by default, so we cannot directly implement it.
When we talk about case-insensitive strings, the initial instinct might be to turn to the string.ToUpper()
and string.ToLower()
functions. However, this approach is suboptimal as it transforms many characters into entirely different letters in the alphabet.
For a genuinely effective case-insensitive containment check function in C#, we have to use alternative approaches. In this article, we will explore different methods to achieve this.
Create a Case-Insensitive Contains
Function Using String.IndexOf
With StringComparison.OrdinalIgnoreCase
in C#
The IndexOf
method in C# is used to find the index of the first occurrence of a specified substring within the string. The crucial aspect for making this search case-insensitive is the use of the StringComparison.OrdinalIgnoreCase
enumeration.
This option tells the method to perform the search without considering the case of the characters.
Now, let’s delve into the syntax:
public int IndexOf(string value, StringComparison comparisonType);
Here, substring
is the target string we are looking for, and comparisonType
is a StringComparison
enumeration that specifies the type of comparison to perform (e.g., case-insensitive).
The IndexOf
method returns the starting index of the substring if found, and by checking if the result is greater than or equal to 0
, we determine if the substring is present in a case-insensitive manner.
Complete code example:
using System;
class Program {
static void Main() {
string mainString = "Hello, C# is awesome!";
string searchString = "c#";
bool result = CaseInsensitiveContains(mainString, searchString);
Console.WriteLine($"Does the string contain '{searchString}'? {result}");
}
public static bool CaseInsensitiveContains(string source, string substring) {
return source.IndexOf(substring, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
Output:
Does the string contain 'c#'? True
In the Main
method, we have a sample string mainString
and a substring searchString
. We then call the CaseInsensitiveContains
function, passing these strings as arguments.
The function uses IndexOf
with StringComparison.OrdinalIgnoreCase
to check if the substring is present in the main string in a case-insensitive manner. The result is displayed in the console, indicating whether the main string contains the specified substring, regardless of the case.
Create a Case-Insensitive Contains
Function Using CultureInfo.CompareInfo.IndexOf
With CompareOptions.IgnoreCase
in C#
An alternative approach to implement a case-insensitive containment check of a string is using CultureInfo.CompareInfo.IndexOf
with CompareOptions.IgnoreCase
.
While the previous method relied on the StringComparison
enumeration, this method leverages culture-aware string comparison, providing more flexibility when dealing with diverse linguistic and cultural requirements.
The CultureInfo.CompareInfo.IndexOf
method is part of the System.Globalization
namespace and allows for culture-sensitive searching within strings.
Let’s examine the syntax:
public int IndexOf(string source, string value, CompareOptions options);
Where:
source
: The string in which to search for the specified substring.value
: The substring to locate within the source string.options
: ACompareOptions
enumeration that specifies the type of comparison to perform. In the context of case-insensitive searching, you would typically useCompareOptions.IgnoreCase
.
Complete code example:
using System;
using System.Globalization;
class Program {
static void Main() {
string mainString = "Hello, C# is amazing!";
string searchString = "c#";
bool result = CaseInsensitiveContains(mainString, searchString);
Console.WriteLine($"Does the string contain '{searchString}'? {result}");
}
public static bool CaseInsensitiveContains(string source, string substring) {
CultureInfo culture = CultureInfo.CurrentCulture;
CompareInfo compareInfo = culture.CompareInfo;
return compareInfo.IndexOf(source, substring, CompareOptions.IgnoreCase) >= 0;
}
}
Output:
Does the string contain 'c#'? True
In this code example, we use the CaseInsensitiveContains
function to determine if the substring is present in the main string in a case-insensitive manner. The CompareInfo
instance is obtained from the current culture, and the IndexOf
method is called with CompareOptions.IgnoreCase
.
This approach is advantageous when dealing with linguistic and cultural variations in string comparisons, ensuring a robust case-insensitive Contains
function in C#.
Create a Case-Insensitive Contains
Function Using String.Contains
With StringComparison.OrdinalIgnoreCase
in C#
Another valuable approach involves using the String.Contains
method with a custom StringComparison
. By supplying StringComparison.OrdinalIgnoreCase
to this parameter, we instruct the method to perform a case-insensitive search.
The String.Contains
method with a custom StringComparison
has the following syntax:
public bool Contains(string value, StringComparison comparisonType);
In our implementation for a case-insensitive Contains
function:
public static bool CaseInsensitiveContains(string source, string substring) {
return source.Contains(substring, StringComparison.OrdinalIgnoreCase);
}
Here, source
represents the string in which we want to search, and substring
is the target string we are looking for. The StringComparison.OrdinalIgnoreCase
option passed to the Contains
method ensures a case-insensitive search.
Complete code example:
using System;
class Program {
static void Main() {
string mainString = "Hello, C# is fantastic!";
string searchString = "c#";
bool result = CaseInsensitiveContains(mainString, searchString);
Console.WriteLine($"Does the string contain '{searchString}'? {result}");
}
public static bool CaseInsensitiveContains(string source, string substring) {
return source.Contains(substring, StringComparison.OrdinalIgnoreCase);
}
}
Output:
Does the string contain 'c#'? True
In this provided code example, the key to achieving case-insensitivity lies in the StringComparison.OrdinalIgnoreCase
option passed as the second argument to the Contains
method. This option instructs the method to perform a case-insensitive search, making it suitable for scenarios where we want to find a substring regardless of the case of the characters.
In the Main
method, we provide sample strings, mainString
and searchString
, and then call the CaseInsensitiveContains
function. The result is stored in the result
variable, indicating whether the main string contains the specified substring in a case-insensitive manner.
Finally, we print the result to the console using Console.WriteLine
, providing a clear indication of whether the substring is contained in the main string, regardless of the case.
Create a Case-Insensitive Contains
Function Using String.Contains
With StringComparison.OrdinalIgnoreCase
in C#
Another powerful approach for achieving case-insensitive string searches in C# involves the use of regular expressions. Regular expressions provide a flexible and robust way to pattern match within strings, and when combined with the Regex.IsMatch
method, we can create an effective case-insensitive Contains
function.
The Regex.IsMatch
method allows us to determine whether a specified regular expression pattern matches a particular input string. By utilizing the Regex.Escape
method to ensure proper handling of special characters and setting the RegexOptions.IgnoreCase
option, we can perform a case-insensitive search.
The Regex.IsMatch
method has the following syntax:
public static bool IsMatch(string input, string pattern, RegexOptions options);
Here:
input
: The input string to search for a match.pattern
: The regular expression pattern to match against the input string.options
: A bitwise combination ofRegexOptions
that modifies the regular expression pattern.
For the case-insensitive search, the RegexOptions.IgnoreCase
option should be specified:
bool result = Regex.IsMatch(source, Regex.Escape(substring), RegexOptions.IgnoreCase);
This usage ensures that the comparison performed by IsMatch
is case-insensitive. The Regex.Escape
method is used to escape any special characters in the substring, ensuring that they are treated literally in the regular expression pattern.
Complete code example:
using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string mainString = "Hello, C# is incredible!";
string searchString = "c#";
bool result = CaseInsensitiveContains(mainString, searchString);
Console.WriteLine($"Does the string contain '{searchString}'? {result}");
}
public static bool CaseInsensitiveContains(string source, string substring) {
return Regex.IsMatch(source, Regex.Escape(substring), RegexOptions.IgnoreCase);
}
}
Output:
Does the string contain 'c#'? True
In this provided code example, we have the CaseInsensitiveContains
function that takes two parameters: source
and substring
.
The heart of this implementation lies in the Regex.IsMatch
method, which determines whether the specified substring matches a regular expression pattern. The regular expression pattern is constructed using Regex.Escape(substring)
to ensure that any special characters in the substring are treated literally, avoiding unintended interpretation as regular expression metacharacters.
The RegexOptions.IgnoreCase
option ensures that the comparison performed by IsMatch
is not sensitive to the case of the characters in the input string.
Then, the CaseInsensitiveContains
function is called in the Main
method, and the result is stored in the result
variable, indicating whether the main string contains the specified substring in a case-insensitive manner.
Conclusion
Creating a case-insensitive Contains
function in C# can be accomplished through various methods. The choice of method depends on factors such as readability, performance, and personal preference.
All the methods discussed in this article give you the flexibility to tailor your case-insensitive string search based on your specific needs.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn