Home > Software engineering >  Detect char differences between two strings and return the strings till the end in C#
Detect char differences between two strings and return the strings till the end in C#

Time:10-28

I have 2 strings

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.";

Basically I want to detect that the word truck is different from car and log the following text in the console exactly as shown:

truck yesterday and it was sick
->
car last year and it was awesome. Mom really liked it.

I don't care about the difference of chars after the first encounter. I just want to log everything after a char index of a string is not the same of another string's char index.

I keep running into issues like accessing out of range elements while attempting to use for and while statements, not detecting changes, messing up the string by returning random elements etc.

CodePudding user response:

We can compare corresponding characters and find index of the first difference. Then we can compute the rest of the strings

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);

Output:

truck yesterday and it was sick
->
car last year and it was awesome. Mom really liked it.
  • Related