Several methods in Java to remove all Spaces in a string

  • 2020-04-01 02:05:49
  • OfStack

Remove whitespace from JAVA    

1. String. The trim ()  

Trim () is minus the first and last space & trim;

2. STR. Replace (" ", ""); Remove all Spaces, including the top, bottom, middle & black;
 
String str = " hell o ";  
String str2 = str.replaceAll(" ", "");  
System.out.println(str2);  
   
3. Or replaceAll(" +",""); Remove all Spaces  

4. The STR =. ReplaceAll (" \ \ s * ", "");  
Can replace most of the white space characters, not limited to the space    
\s can match any &pi of a blank character such as a space, TAB, or page break;

Related articles: