Advertisement
Advertisement


Removing whitespace from strings in Java


Question

I have a string like this:

mysz = "name=john age=13 year=2001";

I want to remove the whitespaces in the string. I tried trim() but this removes only whitespaces before and after the whole string. I also tried replaceAll("\\W", "") but then the = also gets removed.

How can I achieve a string with:

mysz2 = "name=johnage=13year=2001"
2011/03/28
1
693
3/28/2011 7:29:38 AM


replaceAll("\\s","")

\w = Anything that is a word character

\W = Anything that isn't a word character (including punctuation etc)

\s = Anything that is a space character (including space, tab characters etc)

\S = Anything that isn't a space character (including both letters and numbers, as well as punctuation etc)

(Edit: As pointed out, you need to escape the backslash if you want \s to reach the regex engine, resulting in \\s.)

2011/03/28

The most correct answer to the question is:

String mysz2 = mysz.replaceAll("\\s","");

I just adapted this code from the other answers. I'm posting it because besides being exactly what the question requested, it also demonstrates that the result is returned as a new string, the original string is not modified as some of the answers sort of imply.

(Experienced Java developers might say "of course, you can't actually modify a String", but the target audience for this question may well not know this.)

2013/04/16

How about replaceAll("\\s", ""). Refer here.

2011/03/28

One way to handle String manipulations is StringUtils from Apache commons.

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

You can find it here. commons-lang includes lots more and is well supported.

2014/07/20

If you need to remove unbreakable spaces too, you can upgrade your code like this :

st.replaceAll("[\\s|\\u00A0]+", "");
2017/11/20

Source: https://stackoverflow.com/questions/5455794
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]