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

多级指针使用分割字符串

时间:2019-10-09 21:04:29      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:const   使用   color   include   bcd   lib   aaa   malloc   print   

两个赋值指针挖字符串

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

int spitString(const char *buf1,char c,char buf2[10][30],int *count)
{
    char *p = NULL, *pTmp = NULL;
    int tmpcount = 0;
    
    p = buf1;
    pTmp = buf1;
    
    do
    {
        p = strchr(p,c);
        if(p != NULL)
        {
            if(p-pTmp > 0)
            {
                strncpy(buf2[tmpcount],pTmp,p-pTmp);
                buf2[tmpcount][p-pTmp] = \0;
                tmpcount++;
                pTmp = p = p + 1;
            }
        }
        else
        {
            break;
        }
    }while(*p != \0);
    
    *count = tmpcount;
    return 0;
}

int main()
{
    int iRet = 0, i = 0;
    char *p1 = "abcdef,acccd,eeee,aaaa,e3eeee,ssss,";
    char cTem = ,;
    int nCount;
    
    char myArray[10][30];
    
    iRet = spitString(p1,cTem,myArray,&nCount);
    if(iRet != 0)
    {
        printf("fun spitString() error : %d \n",iRet); 
    }
    
    for(i = 0; i < nCount; i++)
    {
        printf("%s \n",myArray[i]);
    }
    return 0;
}

使用第三种内存模型

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

int spitString2(const char *buf1,char c,char **myp,int *count)
{
    char *p = NULL, *pTmp = NULL;
    int tmpcount = 0;
    
    p = buf1;
    pTmp = buf1;
    
    do
    {
        p = strchr(p,c);
        if(p != NULL)
        {
            if(p-pTmp > 0)
            {
                strncpy(myp[tmpcount],pTmp,p-pTmp);
                myp[tmpcount][p-pTmp] = \0;
                tmpcount++;
                pTmp = p = p + 1;
            }
        }
        else
        {
            break;
        }
    }while(*p != \0);
    
    *count = tmpcount;
    return 0;
}

int main()
{
    int iRet = 0, i = 0;
    char *p1 = "abcdef,acccd,eeee,aaaa,e3eeee,ssss,";
    char cTem = ,;
    int nCount;
    
    char **p = NULL;
    p = (char **)malloc(10 * sizeof(char *));
    if(p == NULL)
    {
        return;
    }
    
    for(i = 0; i < 10; i++)
    {
        p[i] = (char *)malloc(30 * sizeof(char));
    }
    
    iRet = spitString2(p1,cTem,p,&nCount);
    if(iRet != 0)
    {
        printf("fun spitString() error : %d \n",iRet); 
    }
    
    for(i = 0; i < nCount; i++)
    {
        printf("%s \n",p[i]);
    }
    
    for( i = 0; i < 10; i++)
    {
        free(p[i]);
    }
    free(p);
    return 0;
}

 

多级指针使用分割字符串

标签:const   使用   color   include   bcd   lib   aaa   malloc   print   

原文地址:https://www.cnblogs.com/wanghao-boke/p/11644309.html

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