首页 > 解决方案 > 从给定列表中查找最长的公共匹配子字符串在一个字符串中

问题描述

我有一个字符串列表,我想在给定字符串中找到它们出现的开始和结束索引。

我想找到原始字符串中存在的最长公共子字符串并只打印它。

这是我的代码:

public static void Main(string[] args)
{
    //This is my original string where I want to find the occurance of the longest common substring
    string str = "will you consider the lic premium of my in-laws for tax exemption";

    //Here are the substrings which I want to compare   
    List<string> subStringsToCompare = new List<string>
    {
        "Life Insurance Premium",
        "lic",
        "life insurance",
        "life insurance policy",
        "lic premium",
        "insurance premium",
        "insurance premium",
        "premium"
    };

    foreach(var item in subStringsToCompare)
    {
        int start = str.IndexOf(item);

        if(start != -1)
        {
            Console.WriteLine("Match found: '{0}' at {1} till {2} character position", item, start, start + item.Length);
        }
    }
}

问题是我出现了 3 次而不是 1 次。我似乎无法弄清楚它从所有子字符串中获取最长的公共匹配子字符串以进行比较的条件。

我得到的输出:

  • 找到匹配项:“lic”在 22 到 25 个字符位置
  • 找到的匹配项:“lic premium”在 22 到 33 个字符位置
  • 找到匹配:26 到 33 个字符位置的“高级”

预期输出:

  • 找到的匹配项:“lic premium”在 22 到 33 个字符位置

.NET 小提琴

标签: c#arraysstringsubstringlongest-substring

解决方案


这是我在评论中提出的建议

public static void Main(string[] args)
{
    //This is my original string where I want to find the occurance of the longest common substring
    string str = "will you consider the lic premium of my in-laws for tax exemption";

    // Here are the substrings which I want to compare
    // (Sorted by length descending) 
    List<string> subStringsToCompare = new List<string>
    {
        "Life Insurance Premium",
        "life insurance policy",
        "insurance premium",
        "life insurance",
        "lic premium",
        "premium",
        "lic"
    };

    foreach(var item in subStringsToCompare)
    {
        int start = str.IndexOf(item);

        if(start != -1)
        {
            Console.WriteLine("Match found: '{0}' at {1} till {2} character position", item, start, start + item.Length);

            break; // Stop at the first match found
        }
    }
}

推荐阅读