码迷,mamicode.com
首页 > 其他好文 > 详细

C提高_day03_两个辅助指针变量挖字符串(强化2)

时间:2015-11-26 01:02:02      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

//两个辅助指针变量挖字符串, 的第三种内存模型
char ** spitString3(char *buf1,char c,int *count)    //**pp二级指针做输入
{

    char *p=NULL, *pTmp = NULL;
    int    tmpcount = 0;
    char **myp=NULL;

    //1 p和ptmp初始化
    p = buf1;
    pTmp = buf1;
    
    //第一遍求出count

    do
    {
        //2 检索符合条件的位置 p后移  形成差值 挖字符串
        p = strchr(p, c);
        if (p != NULL)
        {
            if (p-pTmp > 0)
            {
                tmpcount ++;
                //3重新 让p和ptmp达到下一次检索的条件
                pTmp = p = p + 1;
            }
        }
        else
        {
            break;
        }
    } while (*p!=\0);

    //根据多少行精确分配内存
    myp=(char **)malloc(tmpcount * sizeof(char *));
    if(myp==NULL)
    {
        return NULL;
    }


      /////////////////////////////////////////////////////////

    tmpcount=0;
    //1 p和ptmp初始化
    p = buf1;
    pTmp = buf1;
    
    do
    {
        //2 检索符合条件的位置 p后移  形成差值 挖字符串
        p = strchr(p, c);
        if (p != NULL)
        {
            if (p-pTmp > 0)
            {
                int len=p-pTmp+1;
                myp[tmpcount]=(char *)malloc(len * sizeof(char));
                if(myp==NULL)
                {
                    return NULL;
                }
                strncpy(myp[tmpcount], pTmp,  p-pTmp);
                myp[tmpcount][p-pTmp]=\0;
                tmpcount ++;
                //3重新 让p和ptmp达到下一次检索的条件
                pTmp = p = p + 1;
            }
        }
        else
        {
            break;
        }
    } while (*p!=\0);


    *count = tmpcount;
    return myp;

}

void main()
{
    int i,ret=0;
    char *p1="abcdef,aaa,eeeee,ffffff,a3a3a3,";
    char tmp=,;
    char **p=NULL;
    int nCount;

    p=spitString3(p1,tmp,&nCount);

    if(p==NULL)
    {
        printf("fun spiltString() err:%d \n",ret);
        return ret;
    }

    for(i=0;i<nCount;i++)
    {
        printf("%s \n",p[i]);
    }

    for(i=0;i<nCount;i++)
    {
        free(p[i]);
    }
    free(p);

    printf("%d \n",nCount);
    printf("hello...\n");
    system("pause");

}

C提高_day03_两个辅助指针变量挖字符串(强化2)

标签:

原文地址:http://www.cnblogs.com/zhesun/p/4996343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!