Pergunta

Eu preciso executar Diffs entre cordas de Java. Eu gostaria de ser capaz de reconstruir uma string usando as versões originais de cordas e diff. Alguém já fez isso em Java? Qual biblioteca você usa?

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
Foi útil?

Solução

Esta biblioteca parece fazer o truque: google-diff-match-patch . Ele pode criar uma seqüência de correção de diferenças e permitir que reaplicar o patch.

Editar : Outra solução poderia ser a https: //code.google.com/p/java-diff-utils/

Outras dicas

Apache Commons tem Cordas diff

org.apache.commons.lang.StringUtils

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

Como Torsten diz que você pode usar

org.apache.commons.lang.StringUtils;

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

A biblioteca java diff utills pode ser útil.

Se você precisa lidar com as diferenças entre grandes quantidades de dados e ter as diferenças de forma eficiente comprimido, você pode tentar uma implementação Java do xdelta, que por sua vez implementos RFC 3284 (VCDIFF) para diffs binários (deve trabalhar com cordas também) .

Use a Levenshtein distância e extrair os logs editar a partir da matriz do algoritmo acumula. O artigo ligações Wikipédia para um par de implementações, eu tenho certeza que há uma implementação Java entre em.

Levenshtein é um caso especial do algoritmo Longest Subsequence Comum , você também pode querer ter um olhar para isso.

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;

   }
   }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top