Replace All Spaces in a String : trim, replace vs replaceAll - DevDummy

Latest

Views | Thoughts | Concepts | Techniques

Sunday, June 03, 2018

Replace All Spaces in a String : trim, replace vs replaceAll



Replace All Spaces in a String



trim()

Removes only the leading & trailing spaces.

From Java Doc,
"Returns a string whose value is this string, with any leading and trailing whitespace removed."

System.out.println(" D ev  Dum my ".trim());

"D ev  Dum my"

replace(), replaceAll()

Replaces all the empty strings in the word,

System.out.println(" D ev  Dum my ".replace(" ",""));
System.out.println(" D ev  Dum my ".replaceAll(" ",""));
System.out.println(" D ev  Dum my ".replaceAll("\\s+",""));

"DevDummy"
"DevDummy"
"DevDummy"

Note: "\\s+" is the regular expression similar to the empty space character.

Reference 

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

...

No comments:

Post a Comment