How to revove all whitespces at the end of string in java

Viewed 64

I am trying to remove all white spaces at the end of string (empty line and tab and everything spaces at the end)

public static void main(String[] args) {
        
        String test = "This is test message.\n"
                + "\n"
                + "\n"
                + "\n"
                + "\n"
                + " \n"
                + "";
        System.out.println(test.replaceAll("[\\s\\n]*$", ""));
    }

I tried using trip() and stripTrailing() methods but it did not remove empty lines hence trying with regex. But it is not removing. Any idea why it is not working?

enter image description here

1 Answers

I think that the only way to settle this is to prove that trim() works:

$ cat Test.java 
public class Test {
    public static void main(String[] args) {
        String test = "This is test message.\n"
                + "\n"
                + "\n"
                + "\n"
                + "\n"
                + " \n"
                + "";
        System.out.println(test.trim());
    }
}
$ java Test.java
This is test message.
$ 

If it doesn't work for you, then maybe you are not recompiling your code, or something like that.

For earlier versions of Java use javac Test.java to compile and then java Test to run it. You will get the same output as shown.

Related