How do I remove white-space from the beginning of

2020-02-14 03:30发布

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!

5条回答
等我变得足够好
2楼-- · 2020-02-14 04:03

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 "";
}
查看更多
▲ chillily
3楼-- · 2020-02-14 04:04

As of JDK11 you can use stripLeading:

String result = temp.stripLeading();
查看更多
相关推荐>>
4楼-- · 2020-02-14 04:06

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.

查看更多
萌系小妹纸
5楼-- · 2020-02-14 04:13

You could use:

temp = temp.replaceFirst("^\\s*", "")
查看更多
我想做一个坏孩纸
6楼-- · 2020-02-14 04:18

You could use Commons-lang StringUtils stripStart method.

If you pass null it will automatically trim the spaces.

StringUtils.stripStart(temp, null);
查看更多
登录 后发表回答