java 删除字符串中的所有的空格和局部空格

1.使用Apache的deleteWhitespace函数

Strim或者Trip都是只能去除头部和尾部的空字符串。中间的部分是不能够去除的!

推荐使用ApacheCommonse的StringUtils.deleteWhitespace("a b c"); 删除所有空格。

2.trim、replace、replaceAll

1. trim() 

trim()是去掉首尾空格 



2.str.replace(" ", ""); 去掉所有空格,包括首尾、中间 

String str = " hell o "; 
String str2 = str.replaceAll(" ", ""); 


3.str = .replaceAll("\\s*", ""); 

可以替换大部分空白字符, 不限于空格 
\s 可以匹配空格、制表符、换页符等空白字符的其中任意一个 



4.或者下面的代码也可以去掉所有空格,包括首尾、中间 ,不建议,还不如用第一个模块的函数精确

public String remove(String resource,char ch) 
{ 
StringBuffer buffer=new StringBuffer(); 
int position=0; 
char currentChar; 

while(position
{ 
currentChar=resource.charAt(position++); 
if(currentChar!=ch) buffer.append(currentChar); } return buffer.toString(); 
}

猜你喜欢

转载自blog.csdn.net/qq_35275233/article/details/82823396