1、無論有幾個空格,都輸出為1個空格:
public class DeleteSpace {<br />public static void main(String[] args)throws Exception {<br />String string="new ada dads a ";<br />System.out.println(string.replaceAll(" {2,}", " "));//一個函數搞定<br />StringBuffer sb=new StringBuffer();//用其他方法實現<br />int flag;<br />for(int i=0;i<string.length();i++){<br />flag=0;<br />if(string.charAt(i)!=' '){<br />sb.append(string.charAt(i));<br />}else{<br />flag=1;<br />}<br />try {<br />if(string.charAt(i)==' '&&string.charAt(i+1)!=' '){<br />sb.append(' ');<br />}<br />} catch (Exception e) {<br />continue;<br />}</p><p>}<br />System.out.println(sb);<br />}<br />}<br />
2、去除字串前後的全形空格:
public static void main(String[] args) {<br /> String a = " aaaa aaaa ";<br /> a = a.trim();<br /> while(a.startsWith(" ")){<br /> a = a.substring(1,a.length()).trim();<br /> }<br /> while(a.endsWith(" ")){<br /> a = a.substring(0,a.length()-1).trim();<br /> }<br /> System.out.println(a);<br /> }