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

前端 未结 10 1395
野的像风
野的像风 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:33

    Here's a very short, efficient and easy-to-read version:

    public static String trimTrailing(String str) {
        if (str != null) {
            for (int i = str.length() - 1; i >= 0; --i) {
                if (str.charAt(i) != ' ') {
                    return str.substring(0, i + 1);
                }
            }
        }
        return str;
    }
    

    As an alternative to str.charAt(i) != ' ' you can also use !Character.isWhitespace(str.charAt(i) if you want to use a broader definition of whitespace.

提交回复
热议问题