String str = " Hello Guangzhou ! " Method 1:去掉两端的空格 String newstr1 = str.trim(); System.out.println(newstr1); Hello Guangzhou ! Method 2:去掉所有空格 String newstr2 = str.replaceAll(" ",""); System.out.println(newstr2); HelloGuangzhou!