Java Array Common Prefix longestCommonPrefix(String one, String two)

Here you can find the source of longestCommonPrefix(String one, String two)

Description

Returns the longest common prefix for two Strings or "" if no prefix is shared

License

Open Source License

Parameter

Parameter Description
one The one String
two The other String

Return

The longest common prefix, or ""

Declaration

public static String longestCommonPrefix(String one, String two) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from  w w  w.j a va  2  s  .com*/
     * Returns the longest common prefix for two Strings or <tt>""</tt> if no prefix is shared
     *
     * @param one The one String
     * @param two The other String
     *
     * @return The longest common prefix, or ""
     */
    public static String longestCommonPrefix(String one, String two) {
        if (one.equals(two)) {
            return one;
        }
        if (one.equals("") || two.equals("")) {
            return "";
        }

        String currentPrefix = "";
        int size = 0;
        while (one.startsWith(currentPrefix) && two.startsWith(currentPrefix)) {
            size++;
            currentPrefix = one.substring(0, size);
        }
        return one.substring(0, size - 1);
    }
}

Related

  1. longestCommonContiguousSubstring(String s, String t)
  2. longestCommonPath(String... paths)
  3. longestCommonPrefix(CharSequence str1, CharSequence str2)
  4. longestCommonPrefix(String a, String b)
  5. longestCommonPrefix(String s1, String s2)
  6. longestCommonPrefix(String str1, String str2)
  7. longestCommonPrefix(String... strs)
  8. longestCommonPrefix(String[] strArray)