你会找到一个距离。距离是两个词之间的差异。你可以使用Levenshtein这个。
维基百科:
在信息理论和计算机科学,Levenshtein距离度量是用于测量两个序列之间的差异的字符串。非正式地,两个单词之间的Levenshtein距离是将一个单词换成另一个单词所需的单字符编辑(即插入,删除或替换)的最小数量。
基本用例:
static void Main(string[] args)
{
Console.WriteLine(Levenshtein.FindDistance("Alois", "aloisdg"));
Console.WriteLine(Levenshtein.FindDistance("Alois", "aloisdg", true));
Console.ReadLine();
}
输出
3
2
值越小,越好的比赛。 对于你的例子,你可以使用它,如果匹配比某些事情(比如2)低,你就得到了一个有效的匹配。
我做了一个here:
代码:
public static int FindDistance(string s1, string s2, bool forceLowerCase = false)
{
if (String.IsNullOrEmpty(s1) || s1.Length == 0)
return String.IsNullOrEmpty(s2) ? s2.Length : 0;
if (String.IsNullOrEmpty(s2) || s2.Length == 0)
return String.IsNullOrEmpty(s1) ? s1.Length : 0;
// not in Levenshtein but I need it.
if (forceLowerCase)
{
s1 = s1.ToLowerInvariant();
s2 = s2.ToLowerInvariant();
}
int s1Len = s1.Length;
int s2Len = s2.Length;
int[,] d = new int[s1Len + 1, s2Len + 1];
for (int i = 0; i <= s1Len; i++)
d[i, 0] = i;
for (int j = 0; j <= s2Len; j++)
d[0, j] = j;
for (int i = 1; i <= s1Len; i++)
{
for (int j = 1; j <= s2Len; j++)
{
int cost = Convert.ToInt32(s1[i - 1] != s2[j - 1]);
int min = Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1);
d[i, j] = Math.Min(min, d[i - 1, j - 1] + cost);
}
}
return d[s1Len, s2Len];
}
可惜这不是解决办法,怎么也有像“别尔斯克 - 比亚拉”“新维斯城市”,当你键入没有第二上,和“ - ”没有匹配。 – 2015-03-31 20:59:57