我已经为C++ Qt下载了Google的差异库。
https://code.google.com/archive/p/google-diff-match-patch/
但我并不真正理解如何用它来比较两个字符串。假设我有两个QString。
QString str1="Stackoverflow"
QString str2="Stackrflow"
我理解需要创建diff_match_patch类的dmp对象,然后调用比较方法。那么我该如何获得例如“ove已从第5个位置删除”的结果呢?
我已经为C++ Qt下载了Google的差异库。
https://code.google.com/archive/p/google-diff-match-patch/
但我并不真正理解如何用它来比较两个字符串。假设我有两个QString。
QString str1="Stackoverflow"
QString str2="Stackrflow"
使用方法在API wiki和diff_match_patch.h中有解释。
位置信息不包含在Diff对象中。要获取位置信息,可以遍历列表并计算更改的位置:
即类似于以下代码(未经测试):
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();
}
}