javastringtrimspacesremove-if

How to remove a white space at the end of a string in java?


I am trying to remove exactly one white space at the end of a string. eg. I want " XXXX " to be " XXXX". The trim() method in java removes all leading and trailing whitespaces.

Any help will be appreciated :)


Solution

  • If you just want to trim whitespace at the end, use String#replaceAll() with an appropriate regex:

    String input = " XXXX ";
    String output = input.replaceAll("\\s+$", "");
    System.out.println("***" + input + "***");   // *** XXXX ***
    System.out.println("***" + output + "***");  // *** XXXX***
    

    If you really want to replace just one whitespace character at the end, then replace on \s$ instead of \s+$.