【发布时间】:2018-12-01 05:24:25
【问题描述】:
我有一个字符串列表,我想在给定字符串中找到它们出现的开始和结束索引。
我想找到原始字符串中存在的最长公共子字符串并只打印它。
这是我的代码:
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 个字符位置
- 找到匹配项:“premium”在 26 到 33 个字符位置
预期输出:
- 找到匹配项:“lic premium”在 22 到 33 个字符位置
【问题讨论】:
-
您不能按长度(降序)对
subStringsToCompare进行排序并在找到的第一个匹配项时退出吗?这样,“lic premium”将首先找到并在“lic”和“premium”进入 foreach 循环之前显示。 -
@vc 在我看来并不是万无一失的
-
什么意思?
-
@vc74 我的意思是它仍然在循环后面寻找
lic和premium。如果我得到了比赛怎么解救?这是updated fiddle -
我添加了一个答案来说明我的意思
标签: c# arrays string substring longest-substring