1

Is there a way to compare text in .NET and have it tell you what the differences are? I.e. The difference between "abc123efg" and "abc456efg" is the "123" and "456" starting at index 3 and ending at index 5, etc.

I know I can write the code to do this, but if something already exists in the .NET Framework then I'd like to use that. Alternatively if there is an open source library that does that, then that would be a good option too.

John Mills
  • 10,020
  • 12
  • 74
  • 121

4 Answers4

1

What you're looking for is sort of an "AND" operation on the strings. Here's a good article that does that: http://www.codeproject.com/KB/recipes/DiffAlgorithmCS.aspx

Mrchief
  • 75,126
  • 20
  • 142
  • 189
1

What you're looking for is known as "Diff" (short for "difference"). Nothing like that is built in to the Framework, but there are a number of open source projects like http://diffplex.codeplex.com/ that you can leverage.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
1

The "Generic, Reusable Diff Algorithm in C#" on the code project could be what you're looking for. Source: this SO answer.

Community
  • 1
  • 1
orip
  • 73,323
  • 21
  • 116
  • 148
  • I actually ended up using http://code.google.com/p/google-diff-match-patch/ instead, but I found the link on the SO answer you referenced so I'll mark your answer as accepted. – John Mills Aug 08 '11 at 22:36
0

I think this does the trick:

string a = "abc123efg";
string b = "abc456efg";

var difference = ((from c in a
                  select c).Except(from t in b select t)).ToList();

string result = new string(difference.ToArray());
int startIndex = a.IndexOf(result);
int endIndex = (startIndex + result.Length)-1;
Icarus
  • 63,293
  • 14
  • 100
  • 115