此代码由Java改写而来,字符串支持中文格式的。
string str1 = "中国ab-15"; string str2 = "中国ab-23"; byte[] char1 = Encoding.UTF8.GetBytes(str1); byte[] char2 = Encoding.UTF8.GetBytes(str2); int len1 = char1.Length; int len2 = char2.Length; string maxchar = ""; List<byte> temp = new List<byte>(); int maxl = 0; for (int i = 0; i < len1; i++) for (int j = 0; j < len2; j++) { int pos1 = i; int pos2 = j; int l = 0; temp.Clear(); while (char1[pos1] == char2[pos2]) { l++; temp.Add(char1[pos1]); if (++pos1 > len1 - 1) break; if (++pos2 > len2 - 1) break; } //System.out.println(""+(++loops)+":"+temp); if (l > maxl) { maxl = l; maxchar =Encoding.UTF8.GetString( temp.ToArray()); } } Console.WriteLine("" + maxl + " " + maxchar);