我制作了一个简单的程序,可以从字符串中删除所有空格,但我想要的是一个从字符串开头的中删除空格的程序,如果有,另一个程序从字符串结尾的中删除空格
希望这是有意义的
这是我的c程序,它从所有给出的字符串中删除空格
#include<stdio.h>
int main()
{
int i,j=0;
char str[50];
printf("Donnez une chaine: ");
gets(str);
for(i=0;str[i]!=' ';++i)
{
if(str[i]!=' ')
str[j++]=str[i];
}
str[j]=' ';
printf("nSans Espace: %s",str);
return 0;
}
下方接近
- 首先删除前导的白色字符
- 然后移动字符串
-
然后删除尾随的白色字符。
char *beg = str; char *travel = str; /*After while loop travel will point to non whitespace char*/ while(*travel == ' ') travel++; /*Removes the leading white spaces by shifting chars*/ while(*beg = *travel){ beg++; travel++; } /* travel will be pointing to char*/ if(travel != str) { travel--; beg--; } /*Remove the trailing white chars*/ while(*travel == ' ' && travel != beg) travel--; /*Mark the end of the string*/ if(travel != str) *(travel+1) = ' ';