G
G
gromanev2014-03-29 22:20:19
C++ / C#
gromanev, 2014-03-29 22:20:19

How to search for differences in two strings?

There are two lines, and in the second there is one difference - this is the changed character 0 to 1 (this is all an example). I need to find differences in the text and indexes of these differences. I know about the diff program, but I don't want to resort to using it. Can you advise something? Regulars are good when looking for matches, but when looking for differences - xs, I haven’t come across ... here!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2014-03-30
@r4tz52

One difference? Then what is wrong with this:

static void Main()
    {
        string s1 = "HUFISLKJG74KGLSKIHG7342HGJDSFG0SHFUISEHF23",
         s2 = "HUFISLKJG74KGLSKIHG7342HGJDSFG1SHFUISEHF23";
         
        Console.Write(FindDifference(s1, s2));
    }
    
    static int FindDifference(string s1, string s2)
    {
        for (int i = 0; i < s1.Length; i++)
        {
            if (s1[i] != s2[i])
               return i;
        }
        return -1;
    }

A
akamajoris, 2014-03-30
@akamajoris

Look towards the Levenshtein distance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question