I would like to learn a way to obtain the portions where two strings differ.
Suppose I have these two strings:
String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";
I would like this output: ["x4", "y1", "sb", "length"]
coming from a method receiving s1
and s2
as arguments.
I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).
But this method returns the second string from the index where it begins to differ from the first one.
I really don't know where to start and any advice would be very appreciated.
UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.
This is my code now:
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());
}
Calling getAllSubsequences
on these two strings:
String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"
I receive this string: ["while ( < 5)"]
not ["while (", " < 5)"]
as I would like to obtain. I am not understanding where I am doing wrong.