我有两个字符串
string a = "I bought a new truck yesterday and it was sick";
string b = "I bought a new car last year and it was awesome. Mom really liked it.";
基本上,我想检测单词truck
与car
是否不同,并在控制台中记录以下文本,如图所示:
truck yesterday and it was sick
->
car last year and it was awesome. Mom really liked it.
我不在乎第一次见面后字符的差异。我只想在字符串的字符索引与另一个字符串的字符指数不同之后记录所有内容。
我一直遇到一些问题,比如在尝试使用for和while语句时访问超出范围的元素,没有检测到更改,通过返回随机元素扰乱字符串等等。
我们可以比较相应的字符,找到第一个差异的index
。然后我们可以计算剩下的字符串
string a = "I bought a new";
string b = "I bought a new car last year and it was awesome. Mom really liked it.";
...
int index = Math.Min(a.Length, b.Length);
for (int i = 0; i < Math.Min(a.Length, b.Length); ++i)
if (a[i] != b[i]) {
index = i;
break;
}
string resultA = a.Substring(index);
string resultB = b.Substring(index);
Console.WriteLine(resultA);
Console.WriteLine("->");
Console.WriteLine(resultB);
输出:
truck yesterday and it was sick
->
car last year and it was awesome. Mom really liked it.