删除字符串中的空格字符

来源:互联网 发布:查找重复删除知乎 编辑:程序博客网 时间:2024/06/08 11:08
#include<iostream>#include<assert.h>#include<string.h>using namespace std;char *DeleteBlank(char *s){assert(s!=NULL);int i=0,j=0;//删除字符串开始的空白符  while(s[j] == ' ')j++;   //删除字符串尾部的空白符  int len=strlen(s)-1;  while(s[len] ==' ') len--;  s[len+1]='\0';  while(s[j] !='\0')  {  while(s[j] == ' ')  j++;  //将中间的多个空格变成一个,i!=0是为了防止将头部的连续字符变为1  if(s[j-1] ==' '&&s[j-2] ==' '&&i!=0)  s[i++]=' ';  s[i++]=s[j++];  }  s[i]='\0';return s;}void main(){char str[]="   s abc   ab  ";char *p = DeleteBlank(str);while(*p !='\0')cout<<*p++;}

0 0