仅从字符串的右侧删除空格 [英] Remove whitespaces only from the right side of a String
问题描述
我有一个 String printerName;
长度为 256 个字符.我需要从字符串的右侧删除空格,以便我只得到一个有效的打印机名称.
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.
这个解决方案:
st.replaceAll("\\s+","")
不起作用,因为有效的 printerName 可以有空格.而且我不知道要删除多少个字符,因为可以有很多打印机.对此的最佳解决方案是什么?
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?
推荐答案
如果您只想删除右侧(而不是左侧)的空格,您可以使用:
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()
会解决问题.
这篇关于仅从字符串的右侧删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!