java 去除字符串空格

发布时间 2023-09-12 15:21:05作者: 颂先生

replace方法(str 为字符串)

  • str.replace(" ",""); //去除所有空格,包括首尾、中间 
  • str.replaceAll(" ", ""); //去掉所有空格,包括首尾、中间 
  • str.replaceAll(" +","");  //去掉所有空格,包括首尾、中间
  • str.trim(); //去掉首尾空格
System.out.println(" 44   77  99 0".replace(" ", ""));
System.out.println(" 44 77 99 0".replaceAll(" ", ""));
System.out.println(" 44 77 99 0".replaceAll(" +", ""));
System.out.println(" 44 77 99 0".trim());


依次输出
4477990
4477990
4477990
44   77  99 0