Common prefix between strings

The opposite of finding the common suffix this example will find the longest common prefix between two words using java, guava and apache commons.

Straight up Java

This snippet will find the common prefix of two strings using java. We will take the minimum length of both Strings as the prefix in question won't be greater. Next using a for loop we will iterate and compare each element at the specific position. If the char doesn't match we will break the loop.

@Test
public void find_common_prefix_between_strings_java () {

    String phrase1 = "semicircle";
    String phrase2 = "semiconductor";

    String prefix = "";
    int minLength = Math.min(phrase1.length(), phrase2.length());
    for (int i = 0; i < minLength; i++) {
        if (phrase1.charAt(i) != phrase2.charAt(i)) {
            prefix = phrase1.substring(0, i);
            break;
        }
    }

    assertEquals("semic", prefix);
}

Google Guava

Guava's Strings.commonPrefix will find the longest string prefix of two words.

@Test
public void find_common_prefix_between_strings_guava (){

    String phrase1 = "semicircle";
    String phrase2 = "semiconductor";

    String prefix = Strings.commonPrefix(phrase1, phrase2);

    assertEquals("semic", prefix);
}

Apache Commons

Apache commons StringUtils.getCommonPrefix will find the initial sequence of characters that is common in an array of strings.

@Test
public void find_common_prefix_between_strings_apache_commons () {

    String phrase1 = "semicircle";
    String phrase2 = "semiconductor";

    String prefix = StringUtils.getCommonPrefix(phrase1, phrase2);

    assertEquals("semic", prefix);

}