What must my code look like in order to remove whi

2019-09-16 15:42发布

What must my code look like in order to remove white space in a String in 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.

2条回答
霸刀☆藐视天下
2楼-- · 2019-09-16 16:01

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.
查看更多
Viruses.
3楼-- · 2019-09-16 16:02

The small army of people thinking that \s matches all whitespace are quite simply wrong! Looking in the docs we can see that it matches [ \t\n\x0B\f\r] - a bunch of breaking whitespace (or in other words, just plain old ordinary whitespace.)

Likewise, trim() doesn't match all whitespace either (this is worse, it matches all characters that have a value <= space, most of which aren't technically 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.

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-breaking whitespace 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.)

If this is the case, then try :

String x=splitString.replaceAll("\\p{Z}","");

...where \p{Z} is a shortcut for matching any kind of whitespace, not just non breaking spaces. \p{Separator} is its longer (equivalent) form.

查看更多
登录 后发表回答