c# – Do comparison using String.Contains() disregarding casing

Question:

I need to check if a certain term exists within a string (in SQL it's something like '%termo%' ).

The issue is that I need this to be done without considering the casing of the two strings .

How can I do this? Is there anything native to .NET that allows this kind of comparison?

For example, all comparisons below return false . I need something that makes them return true :

var mainStr = "Joaquim Pedro Soares";

mainStr.Contains("JOA");
mainStr.Contains("Quim");
mainStr.Contains("PEDRO");
mainStr.Contains("PeDro");

Answer:

It's quite simple, use IndexOf() which has a parameter indicating that you want to ignore case sensitivity . Of course, it will return the position where it wants to know if it exists, but then just check if the number is positive, since we know that a negative number means non-existence.

There are those who make an extension method to be available for the String type whenever they need it. There are those who don't like it. If you prefer to do it by hand, just use what's inside the method. You can make an extension method that already uses the fixed comparison option and doesn't parameterize it.

using System;
                    
public class Program {
    public static void Main() {
        var mainStr = "Joaquim Pedro Soares";
        Console.WriteLine(mainStr.Contains("JOA", StringComparison.OrdinalIgnoreCase));
        Console.WriteLine(mainStr.Contains("Quim", StringComparison.OrdinalIgnoreCase));
        Console.WriteLine(mainStr.Contains("PEDRO", StringComparison.OrdinalIgnoreCase));
        Console.WriteLine(mainStr.Contains("PeDro", StringComparison.OrdinalIgnoreCase));
    }
}

namespace System {
    public static class StringExt {
        public static bool Contains(this string source, string search, StringComparison comparison) {
            return source.IndexOf(search, comparison) >= 0;
        }
    }
}

See it working on ideone . And in .NET Fiddle . I also put it on GitHub for future reference .

It is possible to make some optimizations and improvements, like checking if parameters are null or empty.

Scroll to Top