如何在Java中执行字符串差异?

2022-08-31 17:17:20

我需要在Java字符串之间执行差异。我希望能够使用原始字符串和差异版本重建字符串。有人用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

答案 1

这个库似乎可以做到这一点:google-diff-match-patch。它可以从差异中创建补丁字符串,并允许重新应用补丁。

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


答案 2

Apache Commons有String diff

org.apache.commons.lang.StringUtils

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

推荐