我有一个字符串,我想与字符串列表进行比较,以找到最佳匹配。
例如,
string search = "Orange Black Red One Five"
字符串列表可以包含以下内容
l[0] = "Orange Seven Three Black"
l[1] = " Nine Eight Seven Six"
l[2] = " Black Blue Purple Red Five Four Nine Ten"
l[0] contains 2 matches
l[1] contains 0 matches
l[2] contains 3 matches
所以程序会选择l [2]作为最佳匹配,匹配率为60% 我如何比较这样的两个字符串?
答案 0 :(得分:3)
var s = search.Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries);
var res1 = (from string part in l
select new
{
list = part,
count = part.Split(new char[] {' '}).Sum(p => s.Contains(p) ? 1 : 0)
}).OrderByDescending(p=> p.count).First();
Console.Write(res1.count);
答案 1 :(得分:1)
代码:
double Compare(string a, string b)
{
var aWords = a.Split(' ');
var bWords = b.Split(' ');
double matches = (double)aWords.Count(x => bWords.Contains(x));
return matches / (double)aWords.Count();
}
编辑:或者,如果您只想获得匹配计数...
int Matches(string a, string b)
{
var aWords = a.Split(' ');
var bWords = b.Split(' ');
return aWords.Count(x => bWords.Contains(x));
}