两个辅助指针变量, 挖 字符串

定义两个辅助指针变量, 挖 字符串

主调函数分配内存,被调函数分配内存:

char **p = NULL;  //char buf[10][30]

p = (char **)malloc(10 * sizeof(char));  //char * array[10]

if(p == NULL)

{

  return ;

}

for(i = 0; i <10; i++)

{

  p[i] = (char *)malloc(30 * sizeof(char));

}

//free内存

for(i = 0; i < 10; i++)

{

   free(p[i]);

}

free(p);

int spitString(const char *buf1, char c, char **myp, int *count);

int spitString( const char *buf1, char c,char  buf2[10][30], int *count)
/*一个字符串特征为("abcdef,acccd,eeeeee,aaaaa,e3eeeee,ssssss,")
要求写一个函数(接口),输出以下结果
1)以逗号分割字符串,形成二维数组,并把结果传出;
2)把二维数组行数运算结果也传出
*/
#include <stdio.h>
#include <string.h>

int spitString( const char *buf1, char c,char  buf2[10][30], int *count)
{
    const char *p = NULL, *pTmp = NULL;
    int tmpcount = 0;

    //1  p和ptmp初始化
    p = buf1;
    pTmp = buf1;

    do
    {
        //检索符合条件的位置 p后移 形成差值 挖字符串
        p = strchr(p, c);
        if(p != NULL)
        {
            if(p-pTmp > 0)
            {
                strncpy(buf2[tmpcount], pTmp, p-pTmp);
                buf2[tmpcount][p-pTmp] = '\0';
                tmpcount++;

                //3 重新 让p和ptmp达到下一次检索的条件
                pTmp = p = p + 1;
            }
        }
        else
        {
            break ; 
        }
    }while(*p != '\0');

    *count = tmpcount;
    return 0;
}


int main(void)
{
    int ret = 0, i = 0;
    char *p1 = "abcdef,acccd,eeeeee,aaaaa,e3eeeee,ssssss,";
    char cTmp = ',';
    int ncount;
    char myArray[10][30];

    ret = spitString(p1, cTmp, myArray, &ncount);
    if(ret != 0)
    {
        printf("func spitString() err: %d \n", ret);
        return ret;
    }
    for(i = 0; i < ncount; i++)
    {
        printf("%s \n", myArray[i]);
    }

    return 0;
}

 

posted @ 2017-05-02 20:48  Liu_Jing  Views(461)  Comments(0)    收藏  举报