P Ness P Ness - 1 month ago 11
Java Question

Removing trailing spaces?

Let's just say I have a String initialized like this:

String test = "Mr. Johnson, Jr. ";


How would I be able to remove the trailing spaces and not the spaces in the middle?

Before I was doing this:

test = test.replaceAll("\\s+", "");


Output:
Mr.Johnson,Jr.


Expected:
Mr. Johnson, Jr.


And that was deleting ALL blank spaces. Sorry, kind of new to Java. Just started programming not too long ago. xD

Answer

test.replaceAll("\\s+", ""); is a regex operation that replace ALL the matching elements in the string...

You need to trim the string, no regex it

String test = "Mr. Johnson, Jr.              ";
test = test.trim();