比较字符串列表和字符串以查找连续字符匹配的数量

时间:2016-09-30 10:49:12

标签: c# .net algorithm sorting

我确定之前已经完成了,但我真正想做的是有一个方法,在一组多个字符串中找到一个字符串的连续字符匹配,任何匹配小于1个字符匹配,不计算。 (最少2个)。

如果要测试的字符串是“xx Audible 5”,则结果如下

  1. Audible xxx-xxx-5051 NJ -----结果:10(匹配'Audible'和'xx')
  2. yy Audible -----结果:8(声音)
  3. 发声5 xy -----结果:9(空格数,所以匹配是Audible 5)
  4. Audible.com 5 -----结果:7

1 个答案:

答案 0 :(得分:1)

试试这个。这没有优化,但它运作良好

static int FindMatch(string text, string pattern)
    {
        var total = 0;           
        for (int i = 0; i < pattern.Length; i++)
        {
            var max = 0;               
            for (int j = 2; j <= pattern.Length - i; j++)
            {
                var temp = pattern.Substring(i, j);
                if (text.Contains(temp))                   
                    if (max < temp.Length)                        
                        max = temp.Length; 
            }
            total += max;
            if (max > 0)
                i += max-1;
        }
        return total;
    }
  • FindMatch("Audible xxx-xxx-5051 NJ", "xx Audible 5");返回10

  • FindMatch("yy Audible", "xx Audible 5");返回8

  • FindMatch("Audible 5 xy", "xx Audible 5");返回9
  • FindMatch("Audible.com 5", "xx Audible 5");也返回9而不是7,因为我在这个例子中理解会失败空间5&#34; 5&#34;