Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use google-diff-match-patch library in C++ QT?

Tags:

c++

qt

I've downloaded google diff library for C++ Qt.

https://code.google.com/archive/p/google-diff-match-patch/

But I don't really understand how to use it for a simple comparing of two strings. Let assume I have two QStrings.

QString str1="Stackoverflow"
QString str2="Stackrflow"

As I understood I need to create dmp object of diff_match_match class and then call the method for comparing. So what do I do to have for example "ove has deleted from 5 position".

like image 399
P.Tsvetov Avatar asked Dec 14 '25 23:12

P.Tsvetov


1 Answers

Usage is explained in the API wiki and diff_match_patch.h.

The position isn’t contained in the Diff object. To obtain it, you could iterate over the list and calculate the change position:

  • Unchanged substrings and deletes increment the position by the length of the unchanged/deleted substring.
  • Insertions do not alter positions in the original string.
  • Deletes followed by inserts are actually replacements. In that case the insert operation happens at the same position where the delete occured, so that last delete should not increment the position.

i.e. something like this (untested):

auto diffResult = diff_main(str1, str2);
int equalLength = 0;
int deleteLength = 0;
bool lastDeleteLength = 0; // for undoing position offset for replacements
for (const auto & diff : diffResult) {
    if (diff.operation == Operation.EQUAL) {
        equalLength += diff.text.length();
        lastDeleteLength = 0;
    }
    else if (diff.operation == Operation.INSERT) {
        pos = equalLength + deleteLength - lastDeleteLength;
        qDebug() << diff.toString() << "at position" << pos;
        lastDeleteLength = 0;
    }
    else if (diff.operation == Operation.DELETE) {
        qDebug() << diff.toString() << "at position" << equalLength + deleteLength;
        deleteLength += diff.text.length();
        lastDeleteLength = diff.text.length();
    }
}
like image 124
x squared Avatar answered Dec 16 '25 16:12

x squared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!