项目中有这样的需求,用户在两个列表中分别选择两个代码(字母,数字,_),然后需要罗列出2个代码的最大公共部分,加入到ComBox的下拉列表中,如果有多个就可以选择,所以需要快速求取两个字符串的最大公共部分,网上查了一些,发现根本永不了,要么死循环,要么数组越界,真是坑死人,求人不如求己,还是自己写吧,话不多说,先上代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringDemo
{
/// <summary>字符串帮助工具类</summary>
public static class StringUtil
{
/// <summary>获取两个字符串的最大公共部分</summary>
/// <param name="str1">字符串1</param>
/// <param name="str2">字符串2</param>
/// <returns>两个字符串的最大公共部分集合,可能有多个</returns>
public static List<string> GetCommonStr(string str1, string str2) {
List<string> resultList = new List<string>();
//为节省资源,这里取2个字符串中比较短的一个操作
string strShort, strLong;
if (str1.Length <= str2.Length)
{
strShort = str1;
strLong = str2;
}
else {
strShort = str2;
strLong = str1;
}
// 公共部分长度
int subStrLength = 1;
//公共部分长度不能大于短字符串长度
while(subStrLength <= strShort.Length){
for (int i = 0; i < strShort.Length-subStrLength; i++)
{
//循环截取短字符串,每次截取subStrLength长度
string subStr = strShort.Substring(i, subStrLength);
if (strLong.Contains(subStr)) {
//如果长字符串中包含子串,则加入
if (null != resultList &&
resultList.Count > 0 &&
resultList[0].Length < subStrLength) {
//如果原有List中获取到的公共字符串的长度小于新截取的subStr的长度,则清空原有List
resultList = new List<string>();
}
resultList.Add(subStr);
}
}
subStrLength++;
}
return resultList;
}
}
}
以上,这段代码在可以接受参数为空,也可以接受2个相同字符串(当然如果直接判断一下更快),而当正常调用的时候也没问题,比如:
string str1 = "0123000234000045600";
string str2 = "abc456j_fdj4234fkdj0098123";
List<string> resultList = StringUtil.GetCommonStr(str1, str2);
foreach (string item in resultList)
{
Console.WriteLine(item);
}
Console.Read();
输入结果为:
123
234
456
有任何问题,欢迎留言,欢迎转载,转载请注明出处。