Make comparison using String.Contains() disregarding accents and case

Asked

Viewed 1,323 times

4

I need to check how to make a comparison between strings, in C#, using the method Contains() that so disregards the sensitivity of accents and marry of a string.

Example:

var mainStr = "Acentuação";

mainStr.Contains("acentuacao");
mainStr.Contains("ACENTUAção");

Both calls should return true in the case

1 answer

5


To ignore box sensitivity and accents we cannot use any class method String since none is prepared for this. But we can use the same IndexOf() indicating that you wish to ignore the box sensitivity, but he must be of the class CompareInfo that works according to the culture and can ignore the accents with the right configuration. 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.

Can make an extension method to facilitate.

using System;
using System.Globalization;
                    
public class Program {
    public static void Main() {
        var mainStr = "José João";
        Console.WriteLine(mainStr.ContainsInsensitive("JOA"));
        Console.WriteLine(mainStr.ContainsInsensitive("jose"));
        Console.WriteLine(mainStr.ContainsInsensitive("josé"));
    }
}

namespace System {
    public static class StringExt {
        public static bool ContainsInsensitive(this string source, string search) {
            return (new CultureInfo("pt-BR").CompareInfo).IndexOf(source, search, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace) >= 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.

Browser other questions tagged

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