簡體   English   中英

比較字符串列表和字符串以查找連續字符匹配的數量

[英]Compare list of strings and string to find number of consecutive character matches

我確定這之前已經完成了,但我真正想做的是有一種方法可以在一組多個字符串中找到一個字符串的連續字符匹配,其中任何匹配小於 1 個字符匹配,不計算在內。 (最少 2 個)。

如果要測試的字符串是“xx Audible 5”,則結果如下

  1. Audible xxx-xxx-5051 NJ ----- 結果:10(匹配“Audible”和“xx”)
  2. yy Audible ----- 結果:8 (Audible)
  3. Audible 5 xy ----- 結果:9(空格數,所以匹配是 Audible 5)
  4. Audible.com 5 ----- 結果:7

嘗試這個。 這沒有優化,但效果很好

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 因為正如我在這個例子中所理解的那樣會失敗 space 5 " 5"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM