[C#]C#如何求出两个字符串最大的公共部分

    项目中有这样的需求,用户在两个列表中分别选择两个代码(字母,数字,_),然后需要罗列出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

 

    有任何问题,欢迎留言,欢迎转载,转载请注明出处。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值