Split string with delimiters in C

前端 未结 20 1415
你的背包
你的背包 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:12

    Here is my two cents:

    int split (const char *txt, char delim, char ***tokens)
    {
        int *tklen, *t, count = 1;
        char **arr, *p = (char *) txt;
    
        while (*p != '\0') if (*p++ == delim) count += 1;
        t = tklen = calloc (count, sizeof (int));
        for (p = (char *) txt; *p != '\0'; p++) *p == delim ? *t++ : (*t)++;
        *tokens = arr = malloc (count * sizeof (char *));
        t = tklen;
        p = *arr++ = calloc (*(t++) + 1, sizeof (char *));
        while (*txt != '\0')
        {
            if (*txt == delim)
            {
                p = *arr++ = calloc (*(t++) + 1, sizeof (char *));
                txt++;
            }
            else *p++ = *txt++;
        }
        free (tklen);
        return count;
    }
    

    Usage:

    char **tokens;
    int count, i;
    const char *str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
    
    count = split (str, ',', &tokens);
    for (i = 0; i < count; i++) printf ("%s\n", tokens[i]);
    
    /* freeing tokens */
    for (i = 0; i < count; i++) free (tokens[i]);
    free (tokens);
    

提交回复
热议问题