我已经为C ++ Qt下载了谷歌差异库。
https://code.google.com/archive/p/google-diff-match-patch/
但我真的不明白如何使用它来简单比较两个字符串。 假设我有两个QStrings。
QString str1="Stackoverflow"
QString str2="Stackrflow"
据我所知,我需要创建diff_match_match类的dmp对象,然后调用该方法进行比较。 那么我该怎么办才能拥有“ove已经从5位置删除”。
答案 0 :(得分:0)
undefined behavior和API wiki中解释了用法。
位置不包含在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();
}
}