Case insensitive string comparison for Contains in C#


This content was proof-read by Grammarly. You can Try Grammary for FREE

When using the string.contains method , the comparison is done based on the exact string that is passed as parameter. In this case , the comparison is case-sensitive.

using System;
namespace ACConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "This is a WeLcome string";
            var output = input.Contains("Welcome");
            Console.WriteLine(output);
            Console.ReadLine();
        }
    }
}

In the above code snippet , the result is false since the text Welcome is not found in the input string.

How to perform case insensitive string comparison for contains in C# ?

Below is a sample code snippet demonstrating how to do it.

using System;
using System.Globalization;
using System.Threading;

namespace ACConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "This is a WeLcome string";
            var output = Thread.CurrentThread.CurrentCulture.CompareInfo.IndexOf(input, "Welcome", CompareOptions.IgnoreCase);
            Console.WriteLine(output);
            Console.ReadLine();
        }
    }
}
Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

%d bloggers like this: