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

瘦欲@ 提交于 2019-11-29 14:04:07

You could use:

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

You could use Commons-lang StringUtils stripStart method.

If you pass null it will automatically trim the spaces.

StringUtils.stripStart(temp, null);

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

As of JDK11 you can use stripLeading:

String result = temp.stripLeading();

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.

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