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

前端 未结 10 1391
野的像风
野的像风 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 ' '.

    0 讨论(0)
  • 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<Character> 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);
    }
    
    0 讨论(0)
  • 2020-11-30 02:16

    The most practical answer is @Micha's, Ahmad's is reverse of what you wanted so but here's what I came up with in case you'd prefer not to use unfamiliar tools or to see a concrete approach.

    public String trimEnd( String myString ) {
    
        for ( int i = myString.length() - 1; i >= 0; --i ) {
            if ( myString.charAt(i) == ' ' ) {
                continue;
            } else {
                myString = myString.substring( 0, ( i + 1 ) );
                break;
            }
        }
        return myString;
    }
    

    Used like:

    public static void main( String[] args ) {
    
        String s = "    Some text here   ";
        System.out.println( s + "|" );
        s = trimEnd( s );
        System.out.println( s + "|" );
    }
    

    Output:

    Some text here   |
    Some text here|
    
    0 讨论(0)
  • 2020-11-30 02:20

    As of JDK11 you can use stripTrailing:

    String result = str.stripTrailing();
    
    0 讨论(0)
  • 2020-11-30 02:22

    Spring framework gives a useful org.springframework.util.StringUtils.

    trimTrailingWhitespace

    0 讨论(0)
  • 2020-11-30 02:23

    Another option is to use Apache Commons StringUtils, specifically StringUtils.stripEnd

    String stripped = StringUtils.stripEnd("   my lousy string    "," ");
    
    0 讨论(0)
提交回复
热议问题