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

3

I need to check how to make a comparison between strings , in C #, using the Contains() method that disregards both accent sensitivity and case / strong> of a string .

Example:

var mainStr = "Acentuação";

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

Both calls should return true in case

    
asked by anonymous 24.01.2017 / 19:03

1 answer

5

To ignore the box's sensitivity and accents we can not use any method of class String since none is prepared for this. But we can use the same IndexOf() indicating that you want ignore the box sensitivity , but it should be of class < a href="https://msdn.microsoft.com/en-us/library/system.globalization.compareinfo(v=vs.110).aspx"> CompareInfo working according to culture and can ignore accents with the right setting. 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.

You can make an extension method to make it easier.

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;
        }
    }
}

See working 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 / 19:15