基础编程之删除空格
转载请注明作者与出处:franciscolv http://www.cnblogs.com/franciscolv/archive/2011/11/20/2256140.html
package SortSet;
/**
* @author franciscolv
* 干掉字符串前后的空格和字符串中间多余的空格(中间只保留一个)
*/
public class DeleteSpace {
public static void main(String[] args) throws Exception {
String s = " new ada dads a ";
System.out.println(deleteSpace(s));
}
public static String deleteSpace(String s) {
if(s==null)
return null;
StringBuilder sb = new StringBuilder();
int i=0;
while(s.charAt(i++)!=' ')
break;
char tail = s.charAt(i);
for (;i<s.length();i++) {
if (s.charAt(i) != ' ') {
sb.append(s.charAt(i));
tail = s.charAt(i);
} else {
if (tail == ' ')
continue;
sb.append(s.charAt(i));
tail = s.charAt(i);
}
}
if(tail ==' ')
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
}