[C#]C#如何求出两个字符串最大的公共部分
来源:互联网 发布:局域网是什么端口 编辑:程序博客网 时间:2024/05/18 17:23
项目中有这样的需求,用户在两个列表中分别选择两个代码(字母,数字,_),然后需要罗列出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 0
- [C#]C#如何求出两个字符串最大的公共部分
- 求出两个字符串的最大公共字符串
- 求出这两个字符串中最大公共字符串(最大公共字符串:比如 “abc123edf”和"bc123jg"的最大公共字符串是“bc123”)。
- c语言:查找两个字符串的最大公共子串
- 两个字符串的最大公共子字符串
- 两个字符串的最大公共子字符串
- 求出两个字符串的最长公共子串
- 求两个字符串的最大公共字串
- 两个字符串的最大公共子串
- 求两个字符串的最大公共字串
- 两个字符串的最大公共子串
- 两个字符串的最大公共子长度
- 两个字符串中最大的公共字串
- 常见C语言面试题之五:两个字符串的最大公共子字符串
- LCS 两个字符串的最大公共子字符串
- LCS 两个字符串的最大公共子字符串
- 找出两个字符串中最大的公共子字符串
- 求两个字符串最大的公共字串的长度
- http://taiyuan.ganchang.cn/info/index/14097081544494000006.html http://www.rayfile.com/zh-cn/files/f
- 使用AWStats自动分析Nginx日志
- android网络框架retrofit源码解析四
- Struts2上传图片
- 网站加速--服务器编写篇 (下)
- [C#]C#如何求出两个字符串最大的公共部分
- HDU-1003-Max Sum
- 兔子视频 OpenGL 客户端技术解析
- 实现udev/mdev自动挂载与卸载(linux)
- Java 和 Android 中的回调
- spring事务传播机制和嵌套事务
- 创业创意
- Java深入 - Spring 异常处理HandlerExceptionResolver
- HDU 1556 Color the ball