PTA练习题7.1求解给定字符串的前缀。
**
输入格式:
输入数目不定的多对字符串,每行两个,以空格分开。 例如:
filename filepath
Tom Jack
输出格式:
返回两个字符串的最大前缀,例如:
The common prefix is file
No common prefix
输入样例:
filename filepath
Tom Jack
输出样例:
The common prefix is file
No common prefix
/**
* 求解给定字符串的前缀。
* @author czq
* 输入数目不定的多对字符串,每行两个,以空格分开。 例如:
filename filepath
Tom Jack
第一步:创建prefix方法将所需求的字符串作为参数
第二步:用StringBuffer类求解给定字符串的前缀
第三步:charAt方法判断字符串前缀是否相等 用append拼接字符串
*/
public class 求解给定字符串的前缀 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String str1="";
String str2="";
while(sc.hasNext()) {
str1=sc.next();
str2=sc.next();
System.out.println(isPre(str1,str2));
}
}
private static String isPre(String str1, String str2) {
StringBuffer sb = new StringBuffer("");
StringBuffer no = new StringBuffer("No common prefix");
StringBuffer yes = new StringBuffer("The common prefix is ");
boolean hasPre = false;
int i= 0;
while(i<str1.length()&&i<str2.length()) {
if(str1.charAt(i)==str2.charAt(i)) {
hasPre=true;
sb.append(str1.charAt(i));
i++;
}else {
break;
}
}
if(hasPre) {
sb=yes.append(sb);
}else {
sb=no.append(sb);
}
return new String(sb);
}
}