繁体   English   中英

如何找到用户输入的两个输入的通用后缀?

[英]How can I find common suffix of two inputs entered by the user?

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();
    .....

尝试这个:

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());
    }
}

我希望这段代码是不言自明的。

您也可以使用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));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM