我正在使用 C# 来查找两个字符串之间的所有公共子字符串。例如,如果输入是:S1=“需要电子邮件协助”S2=“需要电子邮件协助”
输出应该是“需要帮助电子邮件”
下面的代码返回最长的公共子字符串,但我希望我的代码返回所有公共子字符串。任何帮助深表感谢!
static void commonsubstrings()
{
input1 = "need asssitance with email";
input2 = "email assistance needed"
if (input2.Length > input1.Length)
{
swap = input1;
input1 = input2;
input2 = swap;
}
int k = 1;
String temp;
String longTemp = "";
for (int i = 0; (i <= input1.Length); i++)
{
if ((i == input1.Length))
{
if (longest != null)
{
k = longest.Length + 1;
}
else
{
k = 1;
}
temp = input1.Substring(1, input1.Length - 1);
if (temp.Equals(""))
{
break;
}
if (k <= temp.Length)
{
i = k - 1;
input1 = temp;
if ((longest != null) && (longest.Length > longTemp.Length))
{
longTemp = longest;
}
}
}
holder1 = input1.Substring(0, k);
for (int j = 0; (j < input2.Length) && (j + k <= input2.Length); j++)
{
check1 = input2.Substring(j, k);
if (holder1.Equals(check1))
{
longest = holder1;
break;
}
}
k++;
}
Console.WriteLine(longest);
Console.ReadLine();
}