删除首尾空格并将中间空格合并成一个,代码如下,请采纳
#include
int main()
{
char s[250],*p=s,*q=s;
printf("Enter a string!\n");
gets(s);
while(*p==' ')
p++;
while(*p)
{
if(*p==' ')
{
*q++=*p++;
for(;*p==' ';p++);
}
else
*q++=*p++;
}
*q='\0';
if(*(q-1)==' ')
*(q-1)='\0';
printf("%s\n",s);
return 0;
}
#include
#include
#include
void omitSpace(char *str)
{
char *front = str;
char *last = str;
if(str == NULL) return;
while((*front) == ' ')//omit space in the beginning
{
++front;
}
while((*front) != '\0')
{
if((*front) == ' ')
{
*last = ' ';
while((*front) == ' ')
{
++front;
}
}
else
{
*last = *front;//can also add one if condition to avoid unnecessary assignment:
if(last != front)
{*last = *front;}
++front;
}
++last;//front has pointed to the next char, so don't ++front;
}
*last = '\0';
}
int main()
{
char s[] = {" Hello world, hello C. "};
printf("%s\n",s);
omitSpace(s);
printf("%s\n",s);
return 0;
}
void fun(char* s)
{
int i=0,j=0,f=0;
while(1)
{
if(s[i]=='\0')
{
break;
}
if(s[i]==' ' && f==0)
{
i++;
continue;
}
if(s[i]!=' ')
{
f=1;
s[j++]=s[i++];
continue;
}
else if(s[i]==' ' && s[j-1]==' ' && j>0)
{
i++;
continue;
}
else
{
s[j++]=s[i++];
continue;
}
}
s[j]='\0';
}
void f(char *s){
char *p=s;
while(*s!='\0')
{
while(*s==' ' &&*(s+1)==' '){s++;}
*p=*s;s++;p++;
}
*p='\0';
}
测试一下吧