This recipe shows how to find the longest common prefix between two strings.
Given two strings a and b, find the longest substring that appears at the beginning of both strings.
public class LongestCommonPrefix {
public static String lcp(String a, String b) {
final int N = Math.min(a.length(), b.length());
for (int i = 0; i < N; i++) {
if (a.charAt(i) != b.charAt(i)) {
return a.substring(0, i);
}
}
return a.substring(0, N);
}
public static void main(String[] args) {
final String a = args[0];
final String b = args[1];
System.out.println(lcp(a, b));
}
}
Link To: Java Source Code