Make comparison using String.Contains() disregarding Casing

Asked

Viewed 855 times

4

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

The point is, I need this done without considering Casing of the two strings.

How can I do that? There is something native on . NET that allows this kind of comparison?

For example, all comparisons below return false. I need something to make them come back true:

var mainStr = "Joaquim Pedro Soares";

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

2 answers

3


It’s very simple, use the IndexOf() has a parameter indicating that you want to ignore the box sensitivity. Of course he will return the position from where he is what he wants to know if there is, 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 type String whenever necessary. There are those who do not like it. If you prefer to do it in the hand, just use what is inside the method. You can make an extension method that already uses the fixed comparison option and does not 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;
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also I put on Github for future reference.

It is possible to make some optimizations and improvements, such as checking whether the parameters are null or empty.

  • If I needed to ignore accents, I’d have a way to do it too?

  • @Not Jefersonalmeida, but I think it gives a good new question :)

  • Question asked: http://answall.com/q/179620/101

2

An alternative is to use the class Regex to check the disregarded Casing string, example:

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

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

Console.WriteLine(contains);

Exit:

True

See working here.

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

  • 2

    It has my +1, but I want distance from regex :p Pranks aside, is an interesting alternative even.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.