Method1:去掉首尾空格
String str = "Hello Genius! ";
System.out.println(str.trim());
Method2:去掉所有空格,包括首尾、中间
String str = "Hello Genius! ";
String str2 = str.replaceAll(" ","");
System.out.println(str2);
Method3:去掉所有空格,包括首尾、中间
String str = "Hello Genius! ";
String str3 = str.replaceAll("+","");
System.out.println(str3);
Method4:替换大部分空白字符,不限于空格
String str = "Hello Genius! ";
String str3 = str.replaceAll("\\s*","");
System.out.println(str3);
其中,\s可以匹配空格、制表符、换页符等空白字符
参考:Java正则表达式https://www.runoob.com/java/java-regular-expressions.html