How to trim a String

This example will show how to trim whitespace from a given String using java, guava, apache commons and springframework. This snippets below will trim leading spaces as well as trimming trailing spaces from a String.

Straight up Java

This snippet will show how to trim a string by using the String.trim. By calling the trim function it will remove any leading and trailing whitespace then returning that String.

@Test
public void trim_string_java () {

    String trimmedString = "      Runnin' Down A Dream       ".trim();
    assertEquals("Runnin' Down A Dream", trimmedString);

}

Google Guava

Guava's CharMatcher.WHITESPACE will determine if any character is whitespace and then calling the .trimFrom will omit any of those characters.

@Test
public void trim_string_guava () {

    String trimmedSong = CharMatcher.WHITESPACE.trimFrom("       American Girl       ");
    assertEquals("American Girl", trimmedSong);
}

Apache Commons

Apache commons StringUtils.trim will removes control characters (char <= 32) from both ends of this String.

@Test
public void trim_string_apache_commons () {

    String trimmedSong = StringUtils.trim("       I Need to Know   ");
    assertEquals("I Need to Know", trimmedSong);
}

Spring Framework

Spring's string utility will also handle trim leading and trailing whitespace from the given String.

@Test
public void trim_string_spring () {

    String trimmedSong = org.springframework.util
            .StringUtils.trimWhitespace("       You Got Lucky   ");

    assertEquals("You Got Lucky", trimmedSong);
}