Java:如何比较两个字符串以获得它们不同的部分?

del*_*a85 5 java string string-comparison

我想学习一种方法来获得两个字符串不同的部分。

假设我有这两个字符串:

String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";
Run Code Online (Sandbox Code Playgroud)

我想要这个输出:["x4", "y1", "sb", "length"]来自一个方法接收s1s2作为参数。

我在其他帖子中寻找过类似的东西,但我只找到了指向StringUtils.difference(String first, String second) 的链接

但是这个方法从索引中返回第二个字符串,它开始与第一个不同。
我真的不知道从哪里开始,任何建议将不胜感激。

更新 按照@aUserHimself 的建议,我设法获得了两个字符串中的所有公共子序列,但是这些子序列像一个唯一的字符串一样出现。

这是我现在的代码:

private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}
Run Code Online (Sandbox Code Playgroud)



调用getAllSubsequences这两个字符串:

String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"
Run Code Online (Sandbox Code Playgroud)

我收到这个字符串:["while ( < 5)"]不是["while (", " < 5)"]我想要的。我不明白我哪里做错了。

Sou*_*uly 1

找到两个字符串之间的最长公共子序列。之后,您可以使用 indexOf 获取两个字符串之间的公共字符串的索引,并从两个字符串中获取不常见的值。

例子 :

CICROSOFK
WOCROSFGT
Run Code Online (Sandbox Code Playgroud)

常见的字母是

CROS
Run Code Online (Sandbox Code Playgroud)

查找从 0 到索引 ofSOFT和从index+'SOFT'.lengthto的不同字符串str.length