-3

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 :)

  • 1
    Can you give an example which actually has more than one leading/trailing whitespace character? – Tim Biegeleisen Jan 05 '22 at 09:47
  • " XXXX " . If I use the trim() method it gives me "XXXX" but I only want " XXXX ". I want to remove exactly one whitespace at the end – ItsWhoYouThinkItIs Jan 05 '22 at 09:50
  • 1
    Note that "white space" means the category of characters that represent some kind of empty space. If you wish to remove specifically space characters (Unicode U+0020) and nothing else, then use the term "space character". – Torben Jan 05 '22 at 10:03

3 Answers3

3

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+$.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    This is so much overkill to remove a single space at the end, just `if (s.charAt(s.length() - 1) == ' ') s = s.substring(0, s.length() - 1);` would be sufficient. – Izruo Jan 05 '22 at 09:54
  • @Izruo Yes, you could use a substring operation, and FWIW it would probably be faster than my answer. But if the goal is to remove arbitrary number of whitespaces, then your suggestion becomes less attractive. You would have to do a regex match first before taking a substring. `replaceAll` would be easier. – Tim Biegeleisen Jan 05 '22 at 09:57
  • 1
    @Izruo Do you *really* find that more readable/maintainable than using `replaceAll`? *I* don’t. – Konrad Rudolph Jan 05 '22 at 10:01
3

String#stripTrailing()

Since Java 11, String has a built-in method to to this: String#stripTrailing()

It can be used like

String input = " XXX ";
String output = input.stripTrailing();

Note that, other than String.trim(), this method removes any whitespace at the end of the string, not just spaces.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Izruo
  • 2,246
  • 1
  • 11
  • 23
0

try this solution:

public String trim(String str) { 
 int len = str.length(); 
 int st = 0; 

 char[] val = str.toCharArray(); 

 while ((st < len) && (val[len - 1] <= ' ')) { 
  len--; 
 } 
 return str.substring(st, len); 
}
张翠山
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 05 '22 at 11:18