Make comparison using String.Contains () disregarding casing

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

The point is that I need this 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 to make them return true:

var mainStr = "Joaquim Pedro Soares";

mainStr.Contains("JOA");
mainStr.Contains("Quim");
mainStr.Contains("PEDRO");
mainStr.Contains("PeDro");
Author: LINQ, 2017-01-24

2 answers

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

Has anyone make an extension method to become available for type String whenever they need it. Some people don't like it. If you prefer to do it by hand, just use what is inside method. You can make an extension method that already uses the fixed comparison option and does not parameterize this.

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 working on ideone. And no .NET Fiddle. Also I put on GitHub for future reference .

You can make some optimizations and improvements, such as checking if the parameters are null or empty.

 3
Author: Maniero, 2020-11-23 15:27:04

An alternative is to use the Class Regex to check the string disregarding the casing, example:

string foo = "Gato";
string bar = "gATo";                

bool contains = Regex.IsMatch(bar, foo, RegexOptions.IgnoreCase);

Console.WriteLine(contains);

Output:

True

See working here .

Source: https://stackoverflow.com/a/3355561/5429980

 2
Author: gato, 2017-05-23 12:37:31