Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...