P Ness P Ness - 9 months ago 56
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+", "");


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 Source

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();