题目:
输入字符串,删除首尾的空格。单词中间只留下一个空格。
如输入“ a b c ”输出“a b c"
代码:
public static String test1(String s) {
StringBuffer sb=new StringBuffer(s.trim());
int j=0;
int i;
for(;j<sb.length();){
i=j;
while(sb.charAt(j)==' '&&j<sb.length()-1&&sb.charAt(j+1)==' ')
j++;
if(j>i)
sb.delete(i, j);
j=i;
j++;
}
return new String(sb);
}
char* formatString(char *sourceString) {
if(!sourceString)
return 0;
bool flag=false;
char*out=sourceString;
char* p=out;
char* q=out;
while(*q==' ')
q++;
while(*q!='\0'){
*p=*q;
p++;
q++;
while(*q==' '&&*(q-1)==' ')
q++;
}
if(*(p-1)==' ')
*(p-1)='\0';
else
*p='\0';
return out;
}