如何在列表中找到最接近的字符串

时间:2017-06-09 21:10:22

标签: c# regex string linq equals

如何在列表中找到最接近的字符串:

 var list = new List<string>
 {
    "hello how are you",
    "weather is good today",
    "what is your name",
    "what time is it",
    "what is your favorite color",
    "hello world",
    "how much money you got",
    "where are you",
    "like you"
 };

如果更新的输入是:

  string input = "how are you";

和另一个类型错误:

  string input = "how are ytou";

对于这两种情况都很好:

hello how are you
where are you

甚至是这个结果:

hello how are you
where are you
how much money you got

或至少只是:

hello how are you

我需要它来避免用户请求中出现响应的最小类型错误。

2 个答案:

答案 0 :(得分:0)

一种简单的方法是使用String.Compare来获取

  

两个对手之间的词汇关系

在与输入进行比较后订购可用的项目,并采取最佳匹配,如

string bestMacht = list.OrderBy(s => string.Compare(s, input)).First();

这只是第一种方法,因为应该忽略单词的顺序。 让我们改进这个完整的解决方案。拆分字符串后

string[] splittedInput = input.Split(' ');

您可以使用IEqualityComparer比较单个单词。您可以自由定义每个单词可能失败的字符数(在本例中为2)。

private class NearMatchComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return string.Compare(x, y) < 2;
    }

    public int GetHashCode(string obj)
    {
        return obj.GetHashCode();
    }
}

使用此比较器并比较输入和词典的单词。如果两个单词(按需要定义)匹配(无论顺序),请选择字符串。

List<string> matches = list.Where(s => s.Split(' ')
    .Intersect(splittedInput, new NearMatchComparer()).Count() >= 2)
    .ToList();

结果是潜在匹配列表。

答案 1 :(得分:0)

我会使用Levenshtein距离。这为您提供了不同字符串的值。只需选择你的设置的最小距离。

How to calculate distance similarity measure of given 2 strings?