Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing whitespace from strings in Java

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" 
like image 545
zyamat Avatar asked Mar 28 '11 07:03

zyamat


People also ask

How do I remove spaces from a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.

How do I remove spaces between words in Java?

Java regex remove spaces In Java, we can use regex \\s+ to match whitespace characters, and replaceAll("\\s+", " ") to replace them with a single space.

What is trim () in Java?

Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.


2 Answers

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+","") 
like image 173
Gursel Koca Avatar answered Oct 18 '22 10:10

Gursel Koca


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

like image 42
nitro2k01 Avatar answered Oct 18 '22 09:10

nitro2k01