900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > c语言实现去除字符串首尾空格

c语言实现去除字符串首尾空格

时间:2023-04-05 12:19:12

相关推荐

c语言实现去除字符串首尾空格

字符串内存图如下:

引入头文件:

1 #include<stdlib.h>2 #include<stdio.h>3 #include<string.h>

函数原型:

1 void trim(char *strIn /*in*/, char *strOut /*in*/);

实现方法一:

void trim(char *strIn, char *strOut){int i, j ;i = 0;j = strlen(strIn) - 1;while(strIn[i] == ' ')++i;while(strIn[j] == ' ')--j;strncpy(strOut, strIn + i , j - i + 1);strOut[j - i + 1] = '\0';}

实现方法二:

1 void trim(char *strIn, char *strOut){2 3char *start, *end, *temp;//定义去除空格后字符串的头尾指针和遍历指针45temp = strIn;6 7while (*temp == ' '){8 ++temp;9}10 11start = temp; //求得头指针12 13temp = strIn + strlen(strIn) - 1; //得到原字符串最后一个字符的指针(不是'\0')14 15printf("%c\n", *temp);16 17while (*temp == ' '){18 --temp;19}20 21end = temp; //求得尾指针2223 24for(strIn = start; strIn <= end; ){25 *strOut++ = *strIn++;26}27 28*strOut = '\0';29 }

测试:

1 void main(){2char *strIn = " ak kl p ";3 4char strOut[100];5 6trim(strIn, strOut);7 8printf("*%s*\n",strOut);9 10system("pause");11 }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。