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

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

提交回复
热议问题