Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform string Diffs in Java?

Tags:

java

diff

I need to perform Diffs between Java strings. I would like to be able to rebuild a string using the original string and diff versions. Has anyone done this in Java? What library do you use?

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 
like image 999
Sergio del Amo Avatar asked Sep 25 '08 10:09

Sergio del Amo


People also ask

How do you find the difference between two strings?

To find the difference between 2 Strings you can use the StringUtils class and the difference method. It compares the two Strings, and returns the portion where they differ.

How do you subtract two strings in Java?

toString(); int final_ = Integer. parseInt(addquantity) - Integer. parseInt(subquantity);

How do I compare two characters in a string in Java?

You can compare two Strings in Java using the compareTo() method, equals() method or == operator. The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings.


1 Answers

This library seems to do the trick: google-diff-match-patch. It can create a patch string from differences and allow to reapply the patch.

edit: Another solution might be to https://code.google.com/p/java-diff-utils/

like image 64
bernardn Avatar answered Sep 28 '22 06:09

bernardn