你會找到一個距離。距離是兩個詞之間的差異。你可以使用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