Crescent
Crescent

Reputation: 1

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

Upvotes: 0

Views: 58

Answers (2)

randers
randers

Reputation: 5146

You can also use Google Guava to find a common suffix:

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

Upvotes: 0

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

Try this:

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

I hope, that this piece of code is self-explanatory.

Upvotes: 1

Related Questions