P Ness P Ness - 1 year ago 79
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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download