Parse zip code

This example will show how to parse a zip code from a string using java, guava, and apache commons. A zip code is a group of five or nine numbers that are added to a postal address to assist the sorting of mail. ZIP codes are a system of postal codes used by the United States Postal Service (USPS) since 1963.

Straight up Java

This example will separate a string into zip code pieces using core java String.substring.

Substring

@Test
public void zip_code_parser_java () {

    String zipCode = "535381234";
    
    String zip5 = zipCode.substring(0, 5);
    
    String zip4 = "";
    if (zipCode.length() == 9) {
        zip4 = zipCode.substring(5);
    }
    assertEquals("53538", zip5);
    assertEquals("1234", zip4);
}

Google Guava

This snippet will use guava to split a zip code string based on delimiter using google guava. Splitter will break apart a string based on the delimiter '-' and return an Iterable with the zip5 in position zero and zip4 in second element.

w/ delimiter

@Test
public void zip_code_parser_guava_delimiter () {

    String fullZipCode = "53538-1234";

    Iterable<String> zipCodePieces =
                    Splitter.on(CharMatcher.anyOf("-"))
                    .trimResults()
                    .omitEmptyStrings().split(fullZipCode);
   
    String zip5 = Iterables.get(zipCodePieces, 0);
    String zip4 = Iterables.get(zipCodePieces, 1);

    assertEquals("53538", zip5);
    assertEquals("1234", zip4);
}

Fixed length

Using Guava Splitter again, this snippet will demonstrate how to parse a zip code based on a fixed length.

@Test
public void zip_code_parser_guava_by_fixed_length () {

    String zipCode = "535381234";

    Iterable<String> zipCodePieces =
                    Splitter.fixedLength(5)
                    .trimResults()
                    .omitEmptyStrings().split(zipCode);
   
    String zip5 = Iterables.get(zipCodePieces, 0);
    String zip4 = Iterables.get(zipCodePieces, 1);

    assertEquals("53538", zip5);
    assertEquals("1234", zip4);
}