Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex "Contains" string comparison

I'm developing a C# 4.5 app and I need a function to return true for the following comparison:

"bla LéOnAr d/o bla".ComplexContains("leonardo")

In other words, I need string.Compare(str1, str2, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace) to also check for "contains!

Can anyone help?

like image 258
Leonardo Avatar asked Mar 02 '13 20:03

Leonardo


1 Answers

You could use an appropriate CompareInfo and then CompareInfo.IndexOf(string, string, CompareOptions) and check the result against -1. Sample:

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
        var compareInfo = CultureInfo.InvariantCulture.CompareInfo;
        var options = CompareOptions.IgnoreCase | 
            CompareOptions.IgnoreSymbols |
            CompareOptions.IgnoreNonSpace;

        var haystack = "bla Lé OnAr d/o bla";
        var needle = "leonardo";

        var index = compareInfo.IndexOf(haystack, needle, options);
        Console.WriteLine(index); // 4
    }
}

Or in method form:

private static bool ComplexContains(string source, string value)
{
    var index = CultureInfo.InvariantCulture.CompareInfo.IndexOf
        (source, value, CompareOptions.IgnoreCase | 
         CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace);
    return index != -1;
}
like image 55
Jon Skeet Avatar answered Oct 17 '22 05:10

Jon Skeet