模型-删除空格
求非空字符串长度,两头堵,
i = 0;
j = strlen(p) - 1;
i++,j--,len = j-i;
去除空格,保留新字符串
strncpy(newstr, str+i, ncount);
char *p = " abcdefg "; //p所指向的内存空间在全局区,不能被修改
char buf2[1024] = " abcdefg ";
//重新定义在临时区才能对其进行修改
strncpy(str, str+i, ncount);
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> //求非空格的字符串长度 void getcount(char *str, int *pCount) { char *p = str; int ncount = 0; int i,j = 0; i = 0; j = strlen(p) - 1; if(str == NULL || pCount == NULL) { return; } while(isspace(p[i]) && p[i] != '\0') { i++; } while(isspace(p[j]) && p[j] != '\0') { j--; } ncount = j - i + 1; *pCount = ncount; return; } //去除字符串两端的空格 int trimSpace(char *str, char *newstr) { char *p = str; int ncount = 0; int i,j = 0; i = 0; j = strlen(p) - 1; if(str == NULL || newstr == NULL) { return; } while(isspace(p[i]) && p[i] != '\0') { i++; } while(isspace(p[j]) && p[j] != '\0') { j--; } ncount = j - i + 1; strncpy(newstr, str+i, ncount); newstr[ncount] = '\0'; return 0; } //去除字符串两端的空格 //*str指针所指向的内存空间能否修改? int trimSpace02(char *str) { char *p = str; int ncount = 0; int i,j = 0; i = 0; j = strlen(p) - 1; if(str == NULL ) { return; } while(isspace(p[i]) && p[i] != '\0') { i++; } while(isspace(p[j]) && p[j] != '\0') { j--; } ncount = j - i + 1; //str所指向的内存空间在全局区,不能被修改 //重新定义在临时区才能对其进行修改 strncpy(str, str+i, ncount); str[ncount] = '\0'; return 0; } int main(void) { char *p = " abcdefg "; char buf[1024] = {0}; char buf2[1024] = " abcdefg "; int count = 0; getcount(p, &count); trimSpace(p, buf); //trimSpace02(p);/str所指向的内存空间在全局区,不能被修改 trimSpace02(buf2);//重新定义在临时区才能对其进行修改 printf("count = %d\n", count); printf("buf: %s\n", buf); printf("p: %s\n", p); return 0; }
欢迎加入作者的小圈子
扫描下方左边二维码加入QQ交流群,扫描下方右边二维码关注个人微信公众号并,获取更多隐藏干货,QQ交流群:859800032 微信公众号:Crystal软件学堂
|
作者:Liu_Jing bilibili视频教程地址:https://space.bilibili.com/5782182 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在转载文章页面给出原文连接。 如果你觉得文章对你有所帮助,烦请点个推荐,你的支持是我更文的动力。 文中若有错误,请您务必指出,感谢给予我建议并让我提高的你。 |

浙公网安备 33010602011771号