Split string with delimiters in C

前端 未结 20 1391
你的背包
你的背包 2020-11-21 11:56

How do I write a function to split and return an array for a string with delimiters in the C programming language?

char* str = \"JAN,FEB,MAR,APR,MAY,JUN,JUL,         


        
20条回答
  •  终归单人心
    2020-11-21 12:22

    Try use this.

    char** strsplit(char* str, const char* delim){
        char** res = NULL;
        char*  part;
        int i = 0;
    
        char* aux = strdup(str);
    
        part = strdup(strtok(aux, delim));
    
        while(part){
            res = (char**)realloc(res, (i + 1) * sizeof(char*));
            *(res + i) = strdup(part);
    
            part = strdup(strtok(NULL, delim));
            i++;
        }
    
        res = (char**)realloc(res, i * sizeof(char*));
        *(res + i) = NULL;
    
        return res;
    }
    

提交回复
热议问题