Remove whitespaces only from the right side of a String [duplicate]

别说谁变了你拦得住时间么 提交于 2019-12-13 00:36:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31026144/remove-whitespaces-only-from-the-right-side-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!