Left trim string

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

Google Guava

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

public void trim_leading_spaces_from_string_guava () {
    String leftTrimmedString = CharMatcher.WHITESPACE
            .trimLeadingFrom("       Refugee       ");
    assertEquals("Refugee       ", leftTrimmedString);

Apache Commons

This snippet will remove blanks from the beginning of a string using apache commons. StringUtils.stripStart will strip any whitespace from the start of the specified string.

public void trim_leading_spaces_from_string_apache_commons () {
    String leftTrimmedString = StringUtils
            .stripStart("           The Waiting          ", " ");
    assertEquals("The Waiting          ", leftTrimmedString);

Spring Framework

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

Trim leading whitespace

public void trim_leading_spaces_from_string_spring_with_trimLeadingWhiteSpace () {
    String leftTrimmedString = org.springframework.util
            .StringUtils.trimLeadingWhitespace("      Free Falling          ");
    assertEquals("Free Falling          ", leftTrimmedString);

Trim leading character

public void trim_leading_spaces_from_string_spring_with_trim_leading_character () {
    String leftTrimmedString = org.springframework.util
            .StringUtils.trimLeadingCharacter("      I won't back dowm          ", ' ');
    assertEquals("I won't back dowm          ", leftTrimmedString);