I want to concatenate user input intelligently so that It removes duplicate substring in following way.
- uneasy + easyly = uneasyly
- concat + catalyst = concatalyst
Here is what I am trying to do, not able to figure out what’s missing
public class Concater {
public String concat(String s1, String s2) {
String s = s1;
int L = s2.length();
while (L > 0) {
String common = s2.substring(0, L);
if (s1.endsWith(common)) {
s = s1+common+s2.substring(L);
break;
}
L--;
}
return s;
}
public static void main(String[] args) {
Concater c = new Concater();
System.out.println(c.concat("uneasy", "easyly")+"|expected:uneasyly");
System.out.println(c.concat("concat", "catalyst")+"|expected:concatalyst");
}
}
Output
uneasyeasyly|expected:uneasyly
concatcatalyst|expected:concatalyst
Is there a better way to do it?
Your error is in the line
You are concatenating the whole of s1 plus the common part, which is already contained in s1. Try changing it to
and it should work (not tested, though).