Make comparison using String.Contains () disregarding casing

4

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

The point is that I need to do this without considering the casing of the two strings .

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

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

var mainStr = "Joaquim Pedro Soares";

mainStr.Contains("JOA");
mainStr.Contains("Quim");
mainStr.Contains("PEDRO");
mainStr.Contains("PeDro");
    
asked by anonymous 24.01.2017 / 16:27

2 answers

3

It's quite simple, use IndexOf() that has a parameter indicating that you want to bypass ignore the sensitivity of the box . Of course, it will return to the position where it 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.

Someone makes an extension method available to type String whenever you need it. Some people do not like it. If you prefer to do it on hand, just use what's inside the method. You can do an extension method that already uses the fixed comparison option and do not parametrize 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 running on .NET Fiddle . And at Coding Ground . Also I put it in GitHub for future reference .

Some optimizations and improvements can be made, such as checking whether the parameters are null or empty.

    
24.01.2017 / 16:38
2

An alternative is to use the Regex to check the disregarded casing string, eg:

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

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

Console.WriteLine(contains);

Output:

  

True

See working here .

Source: link

    
24.01.2017 / 17:12