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

字符串内存图如下:

引入头文件:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>


函数原型:
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';
}

实现方法二:
void trim(char *strIn, char *strOut){

char *start, *end, *temp;//定义去除空格后字符串的头尾指针和遍历指针

temp = strIn;

while (*temp == ' '){
++temp;
}

start = temp; //求得头指针

temp = strIn + strlen(strIn) - 1; //得到原字符串最后一个字符的指针(不是'\0')

printf("%c\n", *temp);

while (*temp == ' '){
--temp;
}

end = temp; //求得尾指针

for(strIn = start; strIn <= end; ){
*strOut++ = *strIn++;
}

*strOut = '\0';
}

测试:
void main(){
char *strIn = " ak kl p ";

char strOut[100];

trim(strIn, strOut);

printf("*%s*\n",strOut);

system("pause");
}

 

永不止步步 发表于12-27 13:37 浏览65535次
分享到:

已有0条评论

暂时还没有回复哟,快来抢沙发吧

添加一条新评论

只有登录用户才能评论,请先登录注册哦!

话题作者

永不止步步
金币:67410个|学分:308467个
立即注册
畅学电子网,带你进入电子开发学习世界
专业电子工程技术学习交流社区,加入畅学一起充电加油吧!

x

畅学电子网订阅号