2

I have a String printerName; which is 256 characters long. I need to remove whitespaces from right side of the String so that I get only a valid printer name.

This solution:

st.replaceAll("\\s+","")

doesn't work, because a valid printerName can have a whitespaces. And I don't know how many characters I have to delete, becouse there can be many printers. What's the best solution for this?

LBes
  • 3,366
  • 1
  • 32
  • 66
PRO_gramista
  • 922
  • 1
  • 9
  • 26
  • Duplicate of http://stackoverflow.com/questions/15567010/what-is-a-good-alternative-of-ltrim-and-rtrim-in-java/15567045#15567045 – questionaire Jun 24 '15 at 12:13

1 Answers1

6

If you only want to remove the spaces on the right (but not on the left) you can use:

st.replaceAll("\\s+$", "");

The $ anchor meaning the end of the string.

If you don't mind removing spaces at the beginning of the string as well, then:

st.trim()

will do the trick.

assylias
  • 321,522
  • 82
  • 660
  • 783