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.
Related: Make comparison using String.Contains() disregarding Casing
– Jéf Bueno
@bigown The difference to q I would make is that I would use String.Compare, you know if there is any difference in performance between these 2 methods?
– Jeferson Almeida
@Not Jefersonalmeida, you’d have to test.
– Maniero