import java.util.Scanner;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first string: ");
String one = input.nextLine();
System.out.println("Please enter the second string: ");
String two = input.nextLine();
.....
答案 0 :(得分:1)
试试这个:
import java.util.Scanner;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first string: ");
String one = input.nextLine();
System.out.println("Please enter the second string: ");
String two = input.nextLine();
StringBuilder sb = new StringBuilder();
for (int i = one.length() - 1, j = two.length() - 1; i >= 0 && j >= 0; i--, j--) {
if (one.charAt(i) != two.charAt(j)) {
break;
}
sb.append(one.charAt(i));
}
System.out.println(sb.reverse().toString());
}
}
我希望,这段代码是不言自明的。
答案 1 :(得分:0)
您还可以使用Google Guava查找常用后缀:
com.google.common.base.Strings.commonSuffix(str1, str2)
import java.util.Scanner;
import com.google.common.base.Strings;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first string: ");
String one = input.nextLine();
System.out.println("Please enter the second string: ");
String two = input.nextLine();
System.out.println("Common suffix: " + Strings.commonSuffix(one, two));
}
}