求两个字符串中的公共字符串

时间:2024-03-13 19:00:24


 求两个字符串中的公共字符串,最大公共字符串.

求两个字符串中的公共字符串

C#简单代码如下:

 1 namespace test
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             Console.WriteLine("获取两字符串最大的共同字符");
 8             Console.WriteLine("请输入两个字符串,中间用空格隔开");
 9             string s1=Console.ReadLine();
10             bool isGo = true;
11             if(s1.IndexOf(' ')<0)
12             {
13                 isGo = false;
14                 Console.WriteLine("输入错误");
15             }
16             string[] s = s1.Split(' ');
17 
18             if(s.Count()!=2)
19             {
20                 isGo = false;
21                 Console.WriteLine("获取错误");
22             }
23             if (isGo)
24             {
25                 List<string> maxMatchStr = new List<string>();
26                 string maxPublicStr="";
27                 foreach (string str in GetPublicStr(maxMatchStr, s[0], s[1]))
28                 {
29                     if(str.Length>maxPublicStr.Length)
30                     {
31                         maxPublicStr=str;
32                     }
33                     Console.WriteLine(str);
34                 }
35                 Console.WriteLine("共有公共字符串个数:" + maxMatchStr.Count());
36                 Console.WriteLine("最大的公共字符串:" + maxPublicStr);
37             }
38             Console.ReadKey();
39         }
40         
41         static List<string> GetPublicStr(List<string> matMatchStr, string leftStr, string rightStr)
42         {
43             for (int i = 1; i <= leftStr.Length; i++)
44             {
45                 string operatStr = leftStr.Substring(0, i);
46 
47                 if (rightStr.IndexOf(operatStr) != -1)
48                 {
49                     if (!matMatchStr.Contains(operatStr))
50                     {
51                         matMatchStr.Add(operatStr);
52                     }
53                     string tempLeftStr = leftStr.Substring(leftStr.IndexOf(operatStr) + 1);
54                     GetPublicStr(matMatchStr, tempLeftStr, rightStr);
55                 }
56             }
57             return matMatchStr;
58         }
59     }
60 }

无聊打打小例子,哈哈.

转载于:https://www.cnblogs.com/9546-blog/archive/2012/09/14/GetPublicStr.html