user3676578
user3676578

Reputation: 223

Text comparison algorithm or program?

I am having Two paragraphs which are having sentences, I wanted to compare both the paragraphs and want to show the differences at UI.

Below are the possible use-cases, Which I can think about. Any help in algorithm or code will be appreciable.

enter image description here

Case 1: Word Deleted from str2

String str1 = "Hello I am new How are you";
String str2 = "How are you Hello";

output :
str1 = "<del>Hello I am new</del> How are you";
str2 = "How are you <add>Hello</add>"

Case 2: Word added to str2

String str1 = "Hello How are you what about you";
String str2 = "How are you I am fine what about you";

output :
str1 = "<del>Hello</del> How are you what about you";
str2 = "How are you <add>I am fine</add> what about you"

Case 3: Words are equal

    String str1 = "Hello How are you";
    String str2 = "Hello How rea you";

    output :
    str1 = "Hello How <missmatch>are</missmatch> you";
    str2 = "Hello How <missmatch>rea</missmatch> you"

Upvotes: 1

Views: 1260

Answers (1)

wumpz
wumpz

Reputation: 9191

You could e.g. look at: https://github.com/wumpz/java-diff-utils and to its examples https://github.com/wumpz/java-diff-utils/wiki/Examples. The modification to include your specific tags instead of markup charactars is easy: e.g.

DiffRowGenerator generator = DiffRowGenerator.create()
                .showInlineDiffs(true)
                .mergeOriginalRevised(true)
                .inlineDiffByWord(true)
                .newTag(f -> f?"<span style=\"background-color:#ffc6c6\">":"</span>")
                .oldTag(f -> f?"<span style=\"background-color:#c4ffc3\">":"</span>")
                .columnWidth(10000000)
                .build();

List<DiffRow> rows = generator.generateDiffRows(
                Arrays.asList(lines.get(0)),
                Arrays.asList(lines.get(1)));

System.out.println(rows.get(0).getOldLine());

Upvotes: 1

Related Questions