#include <stdio.h>
#include <string.h>
//trim:remove trailing blacks, tabs, newlines
int trim(char s[]);
int Trim(char s[]);
int main()
{
char a[] = "hello world! ";
int leng = trim(a);
printf("The length is %d, %s@@\n",leng, a);
printf("There are \"%d\" real characters left\n",Trim(a));
printf("%s",a);
}
/*不使用库函数*/
int trim(char s[])
{
/*函数中用到的变量,必须在一开始一次性全部声明*/
int n = 0;
int i;
while(s[n++]!='\0')
;
/* while(s[n++]!='\0')
;
等价于 while(s[n]!='\0')
n++;
*/
for(i=n-2;i>=0;i--)
{
if((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
s[i] = '\0';
else
break;
}
return i;
}
/*使用string.h中的库函数*/
int Trim(char s[])
{
int n;
for(n = strlen(s) - 1; n >= 0; n--)
{
if(s[n]!=' ' && s[n]!='\t' && s[n]!='\n')
break;
s[n+1] = '\0';
}
return n;
}
C语言字符串Trim()函数的实现
最新推荐文章于 2024-06-04 10:59:03 发布