How do I remove white-space from the beginning of a string?

11,165

Solution 1

You could use:

temp = temp.replaceFirst("^\\s*", "")

Solution 2

You could use Commons-lang StringUtils stripStart method.

If you pass null it will automatically trim the spaces.

StringUtils.stripStart(temp, null);

Solution 3

As of JDK11 you can use stripLeading:

String result = temp.stripLeading();

Solution 4

Probably close to the implementation of the suggested Commons-lang StringUtils.stripStart() method:

public static String trimFront(String input) {
    if (input == null) return input;
    for (int i = 0; i < input.length(); i++) {
        if (!Character.isWhitespace(input.charAt(i)))
            return input.substring(i);
    }
    return "";
}
Share:
11,165
sailboatlie
Author by

sailboatlie

Updated on July 28, 2022

Comments

  • sailboatlie
    sailboatlie almost 2 years

    How do I remove white-space from the beginning of a string in Java without removing from the end?

    If the value is:

    String temp = "    hi    "
    

    Then how can I delete only the leading white-space so it looks like this:

    String temp = "hi    "
    

    The current implementation I have is to loop through, checking the first character and creating a substring until the first non-whitespace value is reached.

    Thanks!

  • Brian
    Brian over 11 years
    This won't work with strings that already don't have whitespace. It should be temp.replaceFirst("^\\s*", ""); so that ^ matches the beginning of the string.
  • Tim Bender
    Tim Bender over 11 years
    The OP would also need to make sure the String starts with whitespace characters.
  • Reimeus
    Reimeus over 11 years
    The ^ is only needed when using String.replaceAll. While it will work fine here, it is not needed for String.replaceFirst