Split a string into an integer array in C

10,820

Solution 1

A function with the signature implied in your post is not possible in C, because a function cannot return a dynamically-sized array. Two choices are possible here:

  • Pass an array and the max count into parseString, or
  • Return a pointer representing a dynamically allocated array, along with its actual size.

The first approach limits the size of the array to some number established by the caller; the second approach comes with a requirement to deallocate the array once you are done with it.

The function that follows the first approach would look like this:

void parseString(int data[], size_t maxSize);

The function that follows the second approach would look like this:

int *parseString(size_t *actualSize);

or like this:

void parseString(int ** data, size_t *actualSize);

The second case can be used to combine the two approaches, although the API would become somewhat less intuitive.

As for the parsing itself, many options exist. One of the "lightweight" options is using strtol, like this:

char *end = str;
while(*end) {
    int n = strtol(str, &end, 10);
    printf("%d\n", n);
    while (*end == ',') {
        end++;
    }
    str = end;
}

Demo.

Solution 2

pis a pointer to your string

int parsedArray[1024];                                                     
int nb = 0;

while (nb < sizeof(parsedArray) && *p) {                                   
    parsedArray[nb++] = strtol(p, &p, 10);                                 
    if (*p != ',')                                                         
        break;                                                             
    p++; /* skip, */                                                       
}

nb is the number of parsed int

Solution 3

I would look at the C function strtok() and use that to iterate through your string and extract each element. Use atoi() to resolve each element to an integer.

Share:
10,820
carrot_programmer_3
Author by

carrot_programmer_3

Updated on June 04, 2022

Comments

  • carrot_programmer_3
    carrot_programmer_3 almost 2 years

    I have a comma delimited string in a C app that I'm putting together and I want to split it into an array of integer values. The string could contain any number of comma delimited values so I also dont have an initial size for the array.

    e.g.

    "345,3345,35,75,52,386"
    

    and id like to do something like...

    int parsedArray[] = parseString("345,3345,35,75,52,386");
    

    This would be a breeze in java or c# but I think I'm a little out of my depth when it comes to C. Any ideas of how to achieve this?