Home >Backend Development >C++ >How Can I Perform a Case-Insensitive String Contains Check in C#?

How Can I Perform a Case-Insensitive String Contains Check in C#?

DDD
DDDOriginal
2025-02-02 19:11:11829browse

How Can I Perform a Case-Insensitive String Contains Check in C#?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn