回复 5楼 林月儿
//最长的共同前缀
import java.time.Scanner;
public class Test{
public static void main(String[] args){
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter the first string:");
String ch1 = input.nextLine();
System.out.print("Enter the second string:");
String ch2 = input.nextLine();
int len1 = ch1.length();
int len2 = ch2.length();
int index = 0;
for(int i = 0;i < len1 && i < len2;i++) {
/*
if(ch1.substring(0).compareTo(ch2.substring(0)) != 0) {
System.out.println(ch1 + " and " + ch2 + " have no common prefix");
break;
}
*/
if(ch1.substring(0,i).compareTo(ch2.substring(0,i)) == 0) {
index = i;
}
else
break;
}
System.out.println("The common prefix is " + ch2.substring(0,index));
input.close();
}
}