Get the common Postfix from two String - Java java.lang

Java examples for java.lang:String Algorithm

Description

Get the common Postfix from two String

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String fst = "java2s.com";
        String snd = "java2s.com";
        System.out.println(commonPostfix(fst, snd));
    }//from  w w w.j  av a 2 s. c  o m

    public static String commonPostfix(String fst, String snd) {
        StringBuilder cp = new StringBuilder();
        fst = fst.substring(Math.max(0, fst.length() - snd.length()),
                fst.length());
        snd = snd.substring(Math.max(0, snd.length() - fst.length()),
                snd.length());

        for (int i = fst.length() - 1; i >= 0
                && fst.charAt(i) == snd.charAt(i); i--)
            cp.insert(0, fst.charAt(i));

        return cp.toString();
    }
}

Related Tutorials