版权声明:本BLOG上原创文章未经本人许可,不得转载,否则属于侵权行为 https://blog.csdn.net/weixin_40204595/article/details/84061554
写在前面:本文主要用来积累字符串处理的各种方式。
正文:
1、目的:函数输入一个字符串,要求去掉字符串中的行首和行尾的空格后输出。
实现函数和测试代码如下:
#include <stdio.h>
#include <string.h>
//该函数的作用为:输入一个字符串,删掉行首和行尾的空格
void strtrim (char * p_str )
{
char *p = p_str;
char *q = p_str;
if(NULL == p_str)
return;
//去掉行首的空格
while((*p == ' ')||(*p == '\t'))
{
p++;
}
//赋值
while((p != NULL )&&(*p != '\0'))
{
*q++ = *p++;
//*q = *p;
//q ++;
//p ++;
}
q --;
while((*q == ' ')||(*q == '\t'))
{
q --;
}
//加上结尾
*(q + 1) = '\0';
}
int main(void)
{
char buf[20] = {" abcd efg "}; // 前边两个空格,中间2个空格,后边一个空格
printf("before convert buf:%s\n",buf);
printf("before convert strlen(buf)=%d\n",strlen(buf));
strtrim(buf);
printf("after convert buf:%s\n",buf);
printf("after conver strlen(buf)=%d\n",strlen(buf));
}
测试结果: