Java - Write code to get the prefix length found of common characters at the beginning of the strings.

Requirements

Write code to get the prefix length found of common characters at the beginning of the strings.

Demo

//
// Copyright (C) 2006-2014 Talend Inc. - www.talend.com
///* w  w w.ja v  a2  s  . c o  m*/
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string1 = "book2s.com";
        String string2 = "book2s.com";
        System.out.println(getPrefixLength(string1, string2));
    }

    /**
     * maximum prefix length to use.
     */
    private static final int MINPREFIXTESTLENGTH = 6;

    /**
     * gets the prefix length found of common characters at the beginning of the strings.
     * 
     * @param string1
     * @param string2
     * @return the prefix length found of common characters at the beginning of the strings
     */
    public static int getPrefixLength(final String string1,
            final String string2) {
        final int n = Math.min(MINPREFIXTESTLENGTH,
                Math.min(string1.length(), string2.length()));
        // check for prefix similarity of length n
        for (int i = 0; i < n; i++) {
            // check the prefix is the same so far
            if (string1.charAt(i) != string2.charAt(i)) {
                // not the same so return as far as got
                return i;
            }
        }
        return n; // first n characters are the same
    }
}