Case-Insensitive String Matching in C#
C#'s built-in Contains()
method is case-sensitive. To perform a case-insensitive check for substring presence, you'll need a different approach. The IndexOf()
method offers a solution using the StringComparison.OrdinalIgnoreCase
option:
<code class="language-csharp">string title = "STRING"; bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;</code>
This explicitly defines the comparison type. For cleaner code, an extension method provides a more intuitive solution:
<code class="language-csharp">public static class StringExtensions { public static bool ContainsIgnoreCase(this string source, string toCheck) { return source?.IndexOf(toCheck, StringComparison.OrdinalIgnoreCase) >= 0; } }</code>
Now, case-insensitive checks are straightforward:
<code class="language-csharp">string title = "STRING"; bool contains = title.ContainsIgnoreCase("string");</code>
This extension method enhances readability and simplifies case-insensitive string comparisons, particularly beneficial when working with text where capitalization might vary.
The above is the detailed content of How Can I Perform a Case-Insensitive String Contains Check in C#?. For more information, please follow other related articles on the PHP Chinese website!