如何在Java中执行字符串Diffs?

时间:2020-03-06 14:42:48  来源:igfitidea点击:

我需要在Java字符串之间执行Diffs。我希望能够使用原始的string和diff版本重建字符串。有没有人用Java做到这一点?我们使用什么图书馆?

String a1; // This can be a long text
String a2; // ej. above text with spelling corrections
String a3; // ej. above text with spelling corrections and an additional sentence

Diff diff = new Diff();
String differences_a1_a2 = Diff.getDifferences(a,changed_a);
String differences_a2_a3 = Diff.getDifferences(a,changed_a);    
String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3};
String new_a3 = Diff.build(diffs);
a3.equals(new_a3); // this is true

解决方案

Apache Commons具有String diff

org.apache.commons.lang.StringUtils

StringUtils.difference("foobar", "foo");

使用Levenshtein距离并从算法建立的矩阵中提取编辑日志。 Wikipedia文章链接到几个实现,我敢肯定其中有Java实现。

Levenshtein是最长公共子序列算法的特例,我们可能还想看看。

这个库似乎可以解决问题:google-diff-match-patch。它可以根据差异创建补丁字符串,并允许重新应用补丁。

编辑:另一个解决方案可能是https://code.google.com/p/java-diff-utils/

正如Torsten所说,我们可以使用

org.apache.commons.lang.StringUtils;

System.err.println(StringUtils.getLevenshteinDistance("foobar", "bar"));

如果需要处理大量数据之间的差异并有效地压缩差异,则可以尝试xdelta的Java实现,该实现又为二进制差异实现RFC 3284(VCDIFF)(也应与字符串一起使用)。

java diff utills库可能很有用。