求兩個字串中的公用字串,最大公用字串.
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 }
無聊打打小例子,哈哈.