1. String.trim()
trim() removes the beginning and end spaces
2.str.replace(" ", ""); Remove all spaces, including the beginning and end
String str = " hell o ";
String str2 = str.replaceAll(" ", "");
System.out.println(str2);
3. Or replaceAll(" +",""); Remove all spaces
4.str = .replaceAll("/s*", "");
Can replace most whitespace characters, not limited to spaces
s can match any of the whitespace characters such as spaces, tabs, page breaks, etc.
5. Or the following code can also remove all spaces, including the beginning and end and the middle
public String remove(String resource,char ch) { StringBuffer buffer=new StringBuffer(); int position=0; char currentChar; while(position<resource.length()) { currentChar=resource.charAt(position++); if(currentChar !=ch) buffer.append(currentChar); } return buffer.toString(); }The above is all the content shared by this article, I hope you like it.
Please take some time to share the article with your friends or leave a comment. We will sincerely thank you for your support!