我正在寻找一种简单的方法来辨别字符串是否包含另一个字符串的任何部分(是正则表达式,内置函数我不知道等等)。例如:
string a = "unicorn";
string b = "cornholio";
string c = "ornament";
string d = "elephant";
if (a <comparison> b)
{
// match found ("corn" from 'unicorn' matched "corn" from 'cornholio')
}
if (a <comparison> c)
{
// match found ("orn" from 'unicorn' matched "orn" from 'ornament')
}
if (a <comparison> d)
{
// this will not match
}
像if (a.ContainsAnyPartOf(b))
这样的东西太过于希望了。
另外,我只能访问.NET 2.0。
提前致谢!
答案 0 :(得分:5)
此方法应该有效。您需要为可能匹配的“部分”指定最小长度。我假设你想要寻找至少2的东西,但是你可以根据需要将其设置为高或低。注意:不包括错误检查。
public static bool ContainsPartOf(string s1, string s2, int minsize)
{
for (int i = 0; i <= s2.Length - minsize; i++)
{
if (s1.Contains(s2.Substring(i, minsize)))
return true;
}
return false;
}
答案 1 :(得分:3)
我认为您正在寻找longest common substring的实施方式?
答案 2 :(得分:1)
根据我对该问题的理解,最好的办法是计算Levenshtein(或相关值)距离,并将其与阈值进行比较。
答案 3 :(得分:0)
您的要求有点模糊。
您需要为匹配定义最小长度......但是当您计算出该部分时,实现算法应该不会太困难。
我建议将字符串分解为字符数组,然后使用尾递归来查找部分的匹配。