How to compare two string by marking the differences?

Asked

Viewed 284 times

3

Let’s say I have the strings:

Oi, meu nome é ítalo and Olá, meu nome é ítalo

How to generate a result +- like this:

Hi, my name is Italo

Hello, my name is Italo

The system must somehow mark the part of the string that’s different.

Before anyone asks what I’ve already done, I mean I have no idea how to do it, so I posted the question.

  • 1

    tries to take two richtextbox and go through the text comparing them... while it is different... changes the color of the text.... while equal, maintains... ps. To avoid negative votes, try to be clearer, specify where you want to do this (winforms,wpf,web,etc) these things...

  • 1

    One possibility I see is to do split by spaces and compare words between sentences and mark those that are not in the two arrays resulting from splits

  • 1

    see if that’s what you want to do: https://www.diffchecker.com/diff

  • Exactly that @Rovannlinhalis some code hint?

2 answers

4

You can use a library that manages textual comparison.

The library google-diff-match-patch is available in several languages.

To use the C#version, just download the latest version of the file diff_match_patch.zip and add the file DiffMatchPatch.cs to your project.

The comparison may be made as follows::

string text1 = "Oi, tudo bem?";
string text2 = "Olá, tudo bem?";

var dmp = new diff_match_patch();
var diffs = dmp.diff_main(text1, text2);
var html = dmp.diff_prettyHtml(diffs);

2


I just started doing the code here, but I can’t stop to do that for now, follow the initial code:

    private void Comparar(RichTextBox rtb1, RichTextBox rtb2)
    {
        rtb1.ForeColor = Color.Black;
        rtb1.BackColor = Color.Empty;

        string[] texto1 = rtb1.Text.Split(' ');
        string[] texto2 = rtb2.Text.Split(' ');
        int removidas = 0;
        for (int i =0 ; i < texto1.Length;i++)
        {
            if (texto2.Length > i - removidas)
            if (texto1[i] != texto2[i-removidas])
            {
                rtb1.Select(rtb1.Text.IndexOf(texto1[i], i), texto1[i].Length);
                rtb1.SelectionBackColor = Color.Orange;
                removidas++;
            }
        }

    }

Obviously it’s still just a prototype, but we can start. The result was as follows:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.