找到最接近的字符串匹配

时间:2010-11-04 23:59:52

标签: c# string find

C#WinApp:假设我搜索dtg,但我搜索的项目是dvg,dz,dxg ......所以我希望它能为我找到dvg,因为它更接近我正在搜索的dtg。 我知道有一些NP难算法,但实际上我不想花很多时间在这上面。是否有任何String方法可以做到这一点?或者可以通过一些额外的代码留言来做到这一点?

3 个答案:

答案 0 :(得分:8)

您需要一个描述两个字符串之间差异的指标。一种常见的方法是使用Levenshtein distance,使用几行C#代码快速实现(代码文件可在线获取)。

答案 1 :(得分:1)

您想要使用Soundex。如果我能找到一些代码的链接,我会给你一些。我使用Soundexes进行了拼写检查,这正是你要找的。

与此同时,谷歌搜索应该有所帮助:

http://www.google.com/search?q=C%23+soundex&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

这是一个很好的C#实现:http://www.builderau.com.au/program/csharp/print.htm?TYPE=story&AT=339291792-339028385t-320002002c

答案 2 :(得分:0)

public static string ClosestWord(string word, string[] terms)
{
    string term = word.ToLower();
    List<string> list = terms.ToList();
    if (list.Contains(term))
        return list.Find(t => t.ToLower() == term);
    else
    {
        int[] counter = new int[terms.Length];
        for (int i = 0; i < terms.Length; i++)
        {
            for (int x = 0; x < Math.Min(term.Length, terms[i].Length); x++)
            {
                int difference = Math.Abs(term[x] - terms[i][x]);
                counter[i] += difference;
            }
        }

        int min = counter.Min();
        int index = counter.ToList().FindIndex(t => t == min);
        return terms[index];
    }
}
相关问题