例:“likeyou”和“loveyou” 输出“eyou”
/// <summary>
/// 首先要保证charStr1的指向不变,然后挨个去和charStr2数组的每一个值去做比较,
/// 如果相等,就拿charStr1 的下一个值来和charStr2的下一个值比较
/// (注意,不应该通过循环外层的for循环来让charStr1获取下一个值,而是应该让charStr1的指向不变,通过i+cnt来获取下一个值)
/// 如果不相等,那么循环外层for循环,改变charStr1的指向来获取数组的下一个值,然后重复上边的比较操作
/// </summary>
/// <param name="compareStr1"></param>
/// <param name="compareStr2"></param>
public static string Show(string compareStr1,string compareStr2)
{
//将字符串拆分成字符数组
var charStr1 = compareStr1.ToCharArray();
var charStr2 = compareStr2.ToCharArray();
List<CompareResult> list = new List<CompareResult>();
int cnt = 0;
string str;
//循环charStr1字符数组
for(int i = 0;i < charStr1.Length;i++)
{
cnt = 0;
str = null;
//判断charStr1[i]是否在charStr2数组中有值
//没有值继续下一个循环
if(!charStr2.Contains(charStr1[i]))
{
continue;
}
for(int j = 0;j < charStr2.Length;j++)
{
//i+cnt表示在i不变的而情况下,通过i+cnt来获取下一个值
//如果charStr1的索引值大于等于charStr1的长度,则使外层循环的索引值i等于charStr1的长度
if(i + cnt >= charStr1.Length)
{
i = charStr1.Length;
break;
}
else if(charStr1[i + cnt] == charStr2[j])
{
cnt++;
str += charStr2[j].ToString();
}
else
{
if(cnt > 0)
{
break;
}
}
}
list.Add(new CompareResult { KeyStr = str,KeyCount = cnt });
}
var result = list.OrderByDescending(o => o.KeyCount).FirstOrDefault();
return result.KeyStr;
}
public class CompareResult
{
public string KeyStr { get; set; }
public int KeyCount { get; set; }
}