Question

Je dois effectuer des différences entre les chaînes Java. Je voudrais pouvoir reconstruire une chaîne en utilisant la version originale et les versions diff. Est-ce que quelqu'un a fait cela en Java? Quelle bibliothèque utilisez-vous?

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
Était-ce utile?

La solution

Cette bibliothèque semble faire l'affaire: google-diff-match-patch . Il peut créer une chaîne de correctif à partir de différences et permettre de réappliquer le correctif.

modifier : une autre solution pourrait être de https: //code.google.com/p/java-diff-utils/

Autres conseils

Apache Commons a un diff de chaîne

org.apache.commons.lang.StringUtils

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

Comme le dit Torsten, vous pouvez utiliser

org.apache.commons.lang.StringUtils;

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

La bibliothèque java diff utills peut être utile.

Si vous devez gérer les différences entre de grandes quantités de données et les compresser efficacement, vous pouvez essayer une implémentation Java de xdelta, qui à son tour implémente RFC 3284 (VCDIFF) pour les différences binaires (devrait également fonctionner avec des chaînes). .

Utilisez la distance de Levenshtein et extrayez les journaux d'édition de la matrice créée par l'algorithme. L'article de Wikipédia est lié à quelques implémentations. Je suis sûr qu'il existe une implémentation Java parmi.

Levenshtein est un cas particulier de l’algorithme plus longue sous-séquence commune, mais vous voudrez peut-être aussi jetez un oeil à cela.

public class Stringdiff {
public static void main(String args[]){
System.out.println(strcheck("sum","sumsum"));
}
public static String strcheck(String str1,String str2){
    if(Math.abs((str1.length()-str2.length()))==-1){
        return "Invalid";
    }
    int num=diffcheck1(str1, str2);
    if(num==-1){
        return "Empty";
    }
    if(str1.length()>str2.length()){
        return str1.substring(num);
    }
    else{
        return str2.substring(num);
    }

}

public static int diffcheck1(String str1,String str2)
{
    int i;
    String str;
    String strn;
    if(str1.length()>str2.length()){
        str=str1;
        strn=str2;
    }
    else{
        str=str2;
        strn=str1;
    }
    for(i=0;i<str.length() && i<strn.length();i++){
            if(str1.charAt(i)!=str2.charAt(i)){
                return i;
            }
    }
        if(i<str1.length()||i<str2.length()){
            return i;
        }

    return -1;

   }
   }
scroll top