How to remove only trailing spaces of a string in Java and keep leading spaces?

前端 未结 10 1393
野的像风
野的像风 2020-11-30 01:37

The trim() function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it?

10条回答
  •  粉色の甜心
    2020-11-30 02:06

    The best way in my opinion:

    public static String trimEnd(String source) {
        int pos = source.length() - 1;
        while ((pos >= 0) && Character.isWhitespace(source.charAt(pos))) {
            pos--;
        }
        pos++;
        return (pos < source.length()) ? source.substring(0, pos) : source;
    }
    

    This does not allocate any temporary object to do the job and is faster than using a regular expression. Also it removes all whitespaces, not just ' '.

提交回复
热议问题