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 :)
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 :)
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+$
.
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.
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);
}