编写一个函数,去掉一个字符串前后的空格字符,并在主函数中调用该函数。(c语言)

如题所述

第1个回答  2013-04-07
#include <stdio.h>
#include <string.h>

char *trimStr(char *str)
{
char *tmp = str;
unsigned int len = 0;

if (NULL == str)
{
return NULL;

}

while (' ' == *tmp) ++tmp;

len = strlen(tmp);
str = tmp;

if (len > 0)
{

tmp = str + len - 1;
while (' ' == *tmp) --tmp;
*tmp = '\0';
}

return str;

}

int main(void)
{
char str[20] = " 1234 ";
printf("%s", str);
trimStr(str);
printf("%s", str);
return 0;

}本回答被网友采纳
第2个回答  2018-03-14
#include <stdio.h>
 
void removeBlank(char *p)
{
    char *t;
    t=p;
    while (*t && *t==' ')
    {
        t++;
    }
while ( (*p++=*t++)!='\0' )
{

}
while (*t=='\0'|| *t==' ')
{
*t='\0';
t--;
}
}

int main()
{
    char str[100] ={0};
    gets(str);
    removeBlank(str);
    printf(str);
    return 0;
}
33 44 33 44 55
33 44 33 44 55Press any key to continue

第3个回答  2013-04-08
#include "stdio.h"
fun(char *x)
{int i,j,a;<br>char *p;<br>a=0;<br>for(i=0;x[i];i++)<br> {if((x[i]==32)&&a==0)<br> continue;<br> if(a==0)<br> {a=1;<br> p=&x[i];<br> }
if((x[i]==32)&&a==1)
x[i]='\0';
}
for(j=0;p[j];j++)
{x[j]=p[j];<br> p[j]='\0';<br> }
}
main()
{char *a;</p><p> gets(a);<br> fun(a);<br> puts(a);<br> getch();<br>}
第4个回答  2013-04-08
#include<stdio.h>
char * trim(char *s)
{
char *p,*r;
char *h=s;
p=r=s;
while(*r)r++;//找尾
r--;
while(*r==' ')r--;//找最后一个字 while(*p==' ')p++;//找第一个字
while(p<=r)
*s++=*p++;
*s=0;
return h;
}
void main()
{
char t[100];
printf("输入字符串:");
gets(t);
printf("结果:%s\n",trim(t));
}
相似回答