求兩個字串中的公用字串

來源:互聯網
上載者:User

 求兩個字串中的公用字串,最大公用字串.

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 }

無聊打打小例子,哈哈.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.