5

我想比较两个句子(句子 A 和 B),这样程序就会输出句子 A 对句子 B 所做的更改。例如:

句子 A:It's a lovely day today.
句子 B:It's a very lovely day today, isnt it?

输出:It's a [I:very] lovely day today [C:./,] [I:isnt it?]

其中:
I= 已插入,
C= 已更改

PS:我还没有开始编码,因为我想收集一些关于如何最好地实现这个案例的想法。

4

1 回答 1

2

我想出了下面的代码和这个问题。

条件 不考虑

  1. 从任何列表中删除的项目
  2. 第一个字符差异
  3. 差异项目的重复

如果您有疑问,请检查并告诉我。

public static void main(String[] args) {

    String str1 = "It's a lovely day today.";
    String str2 = "It's 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());

}

输出

It's a [I:very ]lovely day today[C:./,][I: isnt it]
于 2012-09-28T09:42:15.770 回答