压缩字符串中的空格

来源:互联网 发布:在淘宝店铺被限制购买 编辑:程序博客网 时间:2024/06/07 06:04

若输入"    a  b    c ",应输出"a b c"。

void CompressSpace(char *inputStr){char *slow = inputStr;char *fast = inputStr;while (*fast != '\0'){//消除先导的空格while (*fast == ' ' && *fast != '\0'){++fast;}//单词while (*fast != ' ' && *fast != '\0'){*slow = *fast;++slow;++fast;}//消除单词后的空格while (*fast == ' ' && *fast != '\0'){++fast;}//如果不是最后一个单词,要在它后面加一个空格if ( *fast != '\0'){*slow = ' ';++slow;}}*slow = '\0';}

int main(){char s1[] = " a  b     c     ";cout<<s1<<endl;cout<<strlen(s1)<<endl;CompressSpace(s1);cout <<endl;cout<<s1<<endl;cout<<strlen(s1)<<endl;system("pause");return 0;}


0 0