复杂的“Contains"字符串比较
本文关键字:字符串 比较 quot Contains 复杂 | 更新日期: 2023-09-27 18:01:48
我正在开发一个c# 4.5应用程序,我需要一个函数为以下比较返回true:
"bla lsamonar d/o bla".ComplexContains("leonardo")
换句话说,我需要string.Compare(str1, str2, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace)
也检查"包含!
有人能帮忙吗?
您可以使用适当的CompareInfo
,然后使用CompareInfo.IndexOf(string, string, CompareOptions)
并对照-1检查结果。示例:
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
}
}
或以方法形式:
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;
}