为了在java中删除字符串中的空格,我的代码必须是什么样的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19114902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What must my code look like in order to remove white space in a String in java?
提问by Panchotiya Vipul
What must my code look like in order to remove white space in a String in Java?
为了在 Java 中删除字符串中的空格,我的代码必须是什么样的?
I have tried the following:
我尝试了以下方法:
/* Option 1 */ String x=splitString.replaceAll("\s+","");
/* Option 2 */ String x=splitString.trim()
Neither of these give me the result I expect.
这些都没有给我我期望的结果。
采纳答案by Michael Berry
The small army of people thinking that \s
matches allwhitespace are quite simply wrong! Looking in the docswe can see that it matches [ \t\n\x0B\f\r]
- a bunch of breakingwhitespace (or in other words, just plain old ordinary whitespace.)
认为\s
匹配所有空白的一小部分人是完全错误的!查看文档,我们可以看到它匹配[ \t\n\x0B\f\r]
- 一堆破碎的空白(或者换句话说,只是普通的普通空白。)
Likewise, trim()
doesn't match all whitespace either (this is worse, it matches all characters that have a value <= space, most of which aren'ttechnically whitespace) - so giving an example with spaces before and after a string, then calling trim()
on it, is not a comprehensive test by any stretch of the imagination.
同样,trim()
也不匹配所有空格(更糟糕的是,它匹配所有具有值 <= 空格的字符,其中大多数在技术上不是空格)-因此举一个字符串前后空格的示例,然后调用trim()
关于它,不是任何想象力的全面测试。
Given the above, the (regex based) code you've provided will definitely strip all breaking whitespace from the string, so it sounds to me like you have a potentially non-breakingwhitespace character in there. This is especially likely to be the case if you've pulled whatever text it is from some external source rather than just writing the string in code (a portion of a HTML page for example may be the most likely candidate.)
鉴于上述情况,您提供的(基于正则表达式的)代码肯定会从字符串中去除所有中断空格,因此在我看来,您似乎有一个潜在的不间断空格字符。如果您从某个外部来源提取任何文本而不是仅在代码中编写字符串(例如,HTML 页面的一部分可能是最有可能的候选者),则情况尤其可能如此。
If this is the case, then try :
如果是这种情况,请尝试:
String x=splitString.replaceAll("\p{Z}","");
...where \p{Z}
is a shortcut for matching anykind of whitespace, not just non breaking spaces. \p{Separator}
is its longer (equivalent) form.
... where\p{Z}
是匹配任何类型空格的快捷方式,而不仅仅是非中断空格。\p{Separator}
是其较长(等效)形式。
回答by Ashwin Parmar
Try this code will help you!
试试这个代码会帮助你!
String st = " Hello I am White Space ";
System.out.println(st); // Print Original String
//st = st.replaceAll("\s+",""); // Remove all white space and assign to same
st = st.trim(); // It is working fine.
System.out.println(st); // Print after removing all white space.