1. 程式人生 > >java 刪除字串中的所有的空格和區域性空格

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(); 
}