多级指针使用分割字符串

Posted wanghao-boke

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多级指针使用分割字符串相关的知识,希望对你有一定的参考价值。

两个赋值指针挖字符串

#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] = ;
                tmpcount++;
                pTmp = p = p + 1;
            }
        }
        else
        {
            break;
        }
    }while(*p != );
    
    *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 
",iRet); 
    }
    
    for(i = 0; i < nCount; i++)
    {
        printf("%s 
",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] = ;
                tmpcount++;
                pTmp = p = p + 1;
            }
        }
        else
        {
            break;
        }
    }while(*p != );
    
    *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 
",iRet); 
    }
    
    for(i = 0; i < nCount; i++)
    {
        printf("%s 
",p[i]);
    }
    
    for( i = 0; i < 10; i++)
    {
        free(p[i]);
    }
    free(p);
    return 0;
}

 

以上是关于多级指针使用分割字符串的主要内容,如果未能解决你的问题,请参考以下文章

C 语言二级指针案例 ( 多级指针内存释放问题 | 多级指针避免野指针 )

如何使用 C++ 编写具有多级指针的进程内存?

JavaScript 片段

Leetcode刷题100天—1221. 分割平衡字符串( 双指针或贪心)—day31

Leetcode刷题100天—1221. 分割平衡字符串( 双指针或贪心)—day31

一级指针二级指针,或是多级指针访问