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

Time:01-05

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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); 
}
  •  Tags:  
  • Related