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

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

    This code is intended to be read a easily as possible by using descriptive names (and avoiding regular expressions).

    It does use Java 8's Optional so is not appropriate for everyone.

    public static String removeTrailingWhitspace(String string) {
        while (hasWhitespaceLastCharacter(string)) {
            string = removeLastCharacter(string);
        }
        return string;
    }
    
    private static boolean hasWhitespaceLastCharacter(String string) {
        return getLastCharacter(string)
                .map(Character::isWhitespace)
                .orElse(false);
    }
    
    private static Optional getLastCharacter(String string) {
        if (string.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(string.charAt(string.length() - 1));
    }
    
    private static String removeLastCharacter(String string) {
        if (string.isEmpty()) {
            throw new IllegalArgumentException("String must not be empty");
        }
        return string.substring(0, string.length() - 1);
    }
    

提交回复
热议问题