How do I remove white-space from the beginning of

2020-02-14 04:04发布

问题:

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!

回答1:

You could use:

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


回答2:

You could use Commons-lang StringUtils stripStart method.

If you pass null it will automatically trim the spaces.

StringUtils.stripStart(temp, null);


回答3:

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 "";
}


回答4:

As of JDK11 you can use stripLeading:

String result = temp.stripLeading();


回答5:

Blatantly copied from java2s:

text = text.replaceAll("^\\s+", "");

...and modified using @Reimus's answer:

text = text.replaceFirst("^\\s+", "");

I'm not sure of the most efficient method; fwiw, I went with @Reimus's original.