特別注意了
Strim或者Trip都是只能去除頭部和尾部的空字符串。中間的部分是不能夠去除的!
推薦使用ApacheCommonse的StringUtils.deleteWhitespace("a b c"); 刪除所有空格。
如果我自己寫,我會采用foreache遍歷每一個字符串中的字符然后利用StringBuilder追加 或者使用 Replace進行替換,替換的時候對於多個空格可能匹配有問題,利用正則表達式?
網上找到了一個文章,感覺不太全,不過可以參考:
1. String.trim()
trim()是去掉首尾空格
2.str.replace(" ", ""); 去掉所有空格,包括首尾、中間
String str = " hell o ";
String str2 = str.replaceAll(" ", "");
System.out.println(str2);
3.或者replaceAll(" +",""); 去掉所有空格
4.str = .replaceAll("\\s*", "");
可以替換大部分空白字符, 不限於空格
\s 可以匹配空格、制表符、換頁符等空白字符的其中任意一個
5.或者下面的代碼也可以去掉所有空格,包括首尾、中間
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();
}