Right trim string

Just the opposite of trimming a string on the left, this example will trim whitespace from the end of the string using guava, apache commons and spring framework utilities.

Google Guava

This snippet will trim trailing whitespace from a string using guava's CharMatcher. CharMatcher.WHITESPACE will determine whether a character is whitespace then calling trimTrailingFrom will omit all characters that match.

@Test
public void trim_trailing_spaces_from_string_guava () {

    String rightTrimmedString = CharMatcher.WHITESPACE
            .trimTrailingFrom("       Something in the air       ");

    assertEquals("       Something in the air", rightTrimmedString);
}

Apache Commons

This snippet will trim blanks or spaces on the right side of a string using apache commons. StringUtils.stripEnd will strip any whitespace from the end of the specified string.

@Test
public void trim_trailing_spaces_from_string_apache_commons () {

    String rightTrimmedString = StringUtils
            .stripEnd("           Learning to fly          ", " ");

    assertEquals("           Learning to fly", rightTrimmedString);
}

Spring Framework

This snippet will left trim leading whitespace from a string using springframework's StringUtils utility by calling trim trailing whitespace method.

Trim trailing whitespace

@Test
public void trim_trailing_spaces_from_string_spring_with_trimtrailingWhiteSpace () {

    String rightTrimmedString = org.springframework.util
            .StringUtils.trimTrailingWhitespace("      Don't come around here no more          ");

    assertEquals("      Don't come around here no more", rightTrimmedString);
}

Trim trailing character

@Test
public void trim_trailing_spaces_from_string_spring_with_trim_trailing_character () {

    String rightTrimmedString = org.springframework.util
            .StringUtils.trimTrailingCharacter("      The waiting        ", ' ');

    assertEquals("      The waiting", rightTrimmedString);
}