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
Release: 2025-02-02 19:11:11
Original
721 people have browsed it

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>
Copy after login

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>
Copy after login

Now, case-insensitive checks are straightforward:

<code class="language-csharp">string title = "STRING";
bool contains = title.ContainsIgnoreCase("string");</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template