Comparison of sentences in Java

I would like to compare two sentences (sentences A and B) so that the program outputs the changes made in sentence B from sentence A. For example:

offer A: It a lovely day today.
offer B:It a very lovely day today, isnt it?

Output: It a [I:very] lovely day today [C:./,] [I:isnt it?]

where:
      I= INSERTED,
      C= CHANGED

PS: I have not started coding since I want to collect some of your ideas on how to best implement this case.

+5
source share
1 answer

I came up with the code below for this problem too.

Terms Not considered

  • Items removed from any list
  • First difference char
  • duplicate diff element

Please check and let me know if in doubt.

public static void main(String[] args) {

    String str1 = "It a lovely day today.";
    String str2 = "It a very lovely day today, isnt it?";
    StringBuilder builder = new StringBuilder();
    StringBuilder added = new StringBuilder();
    StringBuilder changed = new StringBuilder();

    for (int i = 0; i < str1.length(); i++)
        for (int j = 0; j < str2.length(); j++) {
            if (str1.charAt(i) == str2.charAt(j)) {
                if (added.length() > 0) {
                    builder.append("[I:" + added.toString() + "]");
                    added = new StringBuilder();
                }
                if (changed.length() > 0) {
                    changed.append("[C:" + changed.toString() + "]");
                    changed = new StringBuilder();
                }
                // skip as there is no difference.
                builder.append(str1.charAt(i));
                i++;
                // check if index -1 chars are equal then there is
                // difference start
            } else if (str1.charAt(i - 1) == str2.charAt(j - 1)) {

                // check if end of line
                if ((i + 1 == str1.length())
                        || (str1.charAt(i + 1) == str2.charAt(j + 1))) {

                    changed.append(str1.charAt(i));
                    changed.append("/");
                    changed.append(str2.charAt(j));
                    j++;
                    // everything is added
                    if (i + 1 == str1.length()) {
                        while (j < str2.length() - 1)
                            added.append(str2.charAt(j++));
                    }

                    continue;
                }

                // Go until next equal found
                while (!(str1.charAt(i) == str2.charAt(j))
                        && j < str2.length() - 1) {
                    added.append(str2.charAt(j++));
                }
                j--;

            }
        }
    if (changed.length() > 0) {
        builder.append("[C:" + changed.toString() + "]");
    }
    if (added.length() > 0) {
        builder.append("[I:" + added.toString() + "]");
    }

    System.out.println(builder.toString());

}

Output

It a [I:very ]lovely day today[C:./,][I: isnt it]
+2
source

All Articles