Get the common Prefix for two String - Java java.lang

Java examples for java.lang:String Algorithm

Description

Get the common Prefix for 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(commonPrefix(fst, snd));
    }/*from   ww  w.j  av  a 2 s.co m*/

    public static String commonPrefix(String fst, String snd) {
        StringBuilder cp = new StringBuilder();
        int minLength = Math.min(fst.length(), snd.length());
        fst = fst.substring(0, minLength);
        snd = snd.substring(0, minLength);

        for (int i = 0; i < minLength && fst.charAt(i) == snd.charAt(i); i++)
            cp.append(fst.charAt(i));

        return cp.toString();
    }
}

Related Tutorials