C语言指针——两个辅助指针(取出字符串开头和结尾空格)

1、有一个字符串开头或结尾含有n个空格(”     abcd1234    ”),欲去掉前后空格,返回一个新字符串。

要求1:请自己定义一个接口(函数),并实现功能;70分

要求2:编写测试用例。30分

分析:

两个辅助指针挖字符串--两头堵模型

int trimSpace(char *inbuf, char *outbuf);

*/

#include <stdio.h>

#include <stdlib.h>

#include <string.h>



int getnewbuf(char *inbuf, char* outbuf, int *outlen)

{

    char *p = inbuf;

    int i = 0;

    int j = 0;

    int tmpcount = 0;

    j = strlen(p) - 1; //因为数组从0开始,-1,才是指向于结尾最后一个字符的指针

    printf("j: %d\n", j);

    while (isspace(p[i]) && p[i] != '\0') {

        i++;

    }

    printf("i: %d\n", i);

    while (isspace(p[j]) ) {

        j--;

    }

    printf("j: %d\n", j);

    tmpcount = j - i + 1; //j - i + 1; ==》 17-10 = 7 ==》 7+1 = 8, (数组开头自身1也要加上)

    printf("tmpcount: %d\n", tmpcount); //

    strncpy(outbuf, p+i, tmpcount);

    *outlen = tmpcount;

    

    return 0;

}




int main01(int argc, const char * argv[])

{

    char *inbuf = "          abcd1234          ";

    printf("inbuf:%s\n", inbuf);

    char outbuf[] = {0};

    int outlen;

    getnewbuf(inbuf, outbuf, &outlen);

    

    printf("outbuf: %s, out buf lenth: %d\n", outbuf, outlen);



    printf("Hello, World!\n");

    return 0;

}


猜你喜欢

转载自blog.csdn.net/a6taotao/article/details/80087866