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.
Try this code will help you!
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 callingtrim()
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 :
...where
\p{Z}
is a shortcut for matching any kind of whitespace, not just non breaking spaces.\p{Separator}
is its longer (equivalent) form.