您的位置:首页 > 其它

字符串模型1:打印去掉字符串首尾空格后的字符

2016-03-04 11:35 513 查看
#include <stdio.h>
#include <string.h>

/* 有一个字符串开头或结尾含有n个空格("  helloworld   "), 欲去掉前后空格
* 返回一个新字符串.
* 要求1:自己定义一个接口
* 要求2:编写测试用例
* int trim_space(char *inbuf, char *outbuf);
*/
/*函数如下*/
int trim_space(char *inbuf, char *outbuf, int *pcount)
{
int i = 0, j;       // i指向字符数组第一个字符
int ncount;
char *p = inbuf;

j = strlen(inbuf) - 1;  // j指向最后一个字符

/*-- 字符串去掉首尾空格后的长度 --*/
while ( isspace(inbuf[i]) )
i++;
while ( isspace(inbuf[j]) )
j--;
ncount = j - i + 1;
*pcount = ncount;
/*-------------------------- */

strncpy(outbuf, p+i, ncount);  // 把去掉空格后的字符串复制到outbuf中

return 0;
}

int trim_space2(char *inbuf, char *outbuf)
{

}
/*
int main1(void)
{
char *inbuf = "   helloworld   ";
char outbuf[100] = {0};
printf("before call of func inbuf=%s\n", inbuf);

trim_space(inbuf, outbuf);
printf("after call of func inbuf=%s\n", outbuf);

return 0;
}
*/
int main(void)
{
char *inbuf = "   helloworld   ";
char outbuf[100] = {0};
int count = 0;

trim_space(inbuf, outbuf, &count);
printf("count=%d\n", count);
printf("outbuf=%s\n", outbuf);
printf("strlen(outbuf)=%d\n", strlen(outbuf));

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串操作