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

折月煮酒 提交于 2019-12-29 08:36:09

问题


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.



来源:https://stackoverflow.com/questions/12754582/how-do-i-remove-white-space-from-the-beginning-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!