c# - 从给定列表中查找最长的公共匹配子字符串在一个字符串中
问题描述
我有一个字符串列表,我想在给定字符串中找到它们出现的开始和结束索引。
我想找到原始字符串中存在的最长公共子字符串并只打印它。
这是我的代码:
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 个字符位置
解决方案
这是我在评论中提出的建议
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
}
}
}
推荐阅读
- arm - 如何在 ARM Cortex-A7 上调试 TF-A
- excel - 如何修复 Excel 幻影/幻影选项卡故障?
- python - 如何为 Python 安装 Flask-mysqldb?
- delphi - 如何检查 OCX 接口中的方法是否可用
- qmake - 如何将哈希字符 (#) 添加到 qmake 变量
- mysql - MySQL - GROUP 多行同时保留差异
- python - 在文件名中查找交替(字母或数字)+字母模式
- laravel - 如何检查正在执行的控制器数据对象?
- swift - 如何更改 Tableview 的 UIContextualAction 的图像色调颜色?
- java - MongoDB JAVA:查询时是否有任何可能的异常?