Reputation: 401
I have two String
s, for example:
s1=abcd
s2=abfg
I want to compare these two String
s and print the starting String
until they are different. For instance, I want to print ab
in this case. How can I get this result?
Upvotes: 1
Views: 128
Reputation: 176
You can use substring(int startIndex, int endIndex) to split the strings from every position,
String s1 = "abcd";
String s2 = "abfg";
List<String> stringlist = new ArrayList<String>();
String shortest = null;
if(s1.length() <= s2.length()){
shortest = s2;
}
for(int i = 1 ; i<shortest.length() ; i++){
if(s1.substring(0,i).equals(s2.substring(0,i))){
stringlist.add(s1.substring(0,i));
}
}
System.out.println(stringlist.get(stringlist.size()-1));
Upvotes: 0
Reputation: 411
As @IvanPronin mentioned, If you do this very frequently you can use the indexOfDifference of StringUtils:
String s1 = "abcf";
String s2 = "abdf";
System.out.println(s1.substring(0, StringUtils.indexOfDifference(s1, s2)));
but you have to download the jar and include it. Download link
Upvotes: 1
Reputation: 89
package simple;
public class Simple {
public static void main(String[] args) {
String s1 = "abcf";
String s2 = "abdf";
StringBuilder sb = new StringBuilder();
int k = s1.length() < s2.length() ? s1.length() : s2.length();
for (int i = 0; i < k; i++) {
if (s1.charAt(i) == s2.charAt(i)) {
sb.append(s1.charAt(i));
} else {
break;
}
}
System.out.print(sb);
}
}
Upvotes: 1