Removing whitespace from strings in Java

Removing whitespace from strings in Java

st.replaceAll(\s+,) removes all whitespaces and non-visible characters (e.g., tab, n).


st.replaceAll(\s+,) and st.replaceAll(\s,) produce the same result.

The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one.


Assign the value to a variable, if not used directly:

st = st.replaceAll(\s+,)
replaceAll(\s,)

w = Anything that is a word character

W = Anything that isnt a word character (including punctuation etc)

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

S = Anything that isnt 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.)

Removing whitespace from strings in Java

The most correct answer to the question is:

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

I just adapted this code from the other answers. Im 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 cant actually modify a String, but the target audience for this question may well not know this.)

Leave a Reply

Your email address will not be published.