How to remove trailing spaces from string in Java

1 Answer

0 votes
public class MyClass {
    public static String trimEnd(String s) {
        return s.replaceFirst("\\s+$", "");
    }
    public static void main(String args[]) {
        String s = "java   ";
        
        System.out.println(s.length());
        
        s = trimEnd(s);
        
        System.out.println(s.length());
        System.out.println(s);
    }
}



/*
run:

7
4
java

*/

 



answered Nov 1, 2020 by avibootz

Related questions

1 answer 203 views
1 answer 181 views
1 answer 167 views
1 answer 135 views
1 answer 135 views
1 answer 223 views
...