Search code examples
cstringcastingcharuint32-t

How to convert comma separated char* to uint32_t[] array in C


I want to convert a comma separated char* to an uint32_array[] in C. Is there an easy method/routine to do that?

I already spend a lot of time on SO and found many solutions on C++, but not an C like that : Parsing a comma-delimited std::string But I think it is not a good solution to cast from char* to string to string stream to vector and work with the vector.

char input[] = "1 , 2 , 34, 12, 46, 100";

to

uint32_t output[] = { 1 , 2 , 34, 12, 46, 100 };

I would appreciate any kind of help. Thanks a lot.


Solution

  • Here's a recursive algorithm that only makes a single pass. It allocates at the deepest level and fills in on the way out:

    int *cvt(char *input, int *level)
    {
        char *cp = strtok(input, ", ");
        if (cp == NULL) {
            /* No more separators */
            return (int *) malloc(sizeof(int) * *level);
        }
    
        int my_index = -1;
        int n;
        if (sscanf(cp, "%d", &n) == 1) {
            my_index = *level;
            *level += 1;
        } else {
            printf("Invalid integer token '%s'\n", cp);
        }
        int *array = cvt(NULL, level);
        if (my_index >= 0) {
            array[my_index] = n;
        }
        return array;
    }
    

    Call with:

    int main(int ac, char **av)
    {
        char input[] = "1, 2, bogus, 4, 8, 22, 33, 55";
        int n_array = 0;
        int *array = cvt(input, &n_array);
    
        int i;
        printf("Got %d members:\n", n_array);
        for (i = 0; i < n_array; ++i)
            printf("%d ", array[i]);
        printf("\n");
    
        return 0;
    }