Search code examples
carraysstringstrtok

How to split a numeric string and then store it in an int array in c?


I want to split a numeric string into separate numbers and then store each number in an integer array. For example we have this numeric string: 1 2 3 and I want the output to be:

arr[0] = 1
arr[1] = 2
arr[2] = 3

I am using the strtok() function. However , the code below does not display the expected results:

int main()
{
    char b[] = "1 2 3 4 5";
    char *p = strtok(b," ");
    int init_size = strlen(b);
    int arr[init_size];
    int i = 0;

    while( p != NULL)
    {
       arr[i++] = p;
       p = strtok(NULL," ");
    }

    for(i = 0; i < init_size; i++)
        printf("%s\n", arr[i]);

return 0;
}

Solution

  • You have to convert string to int using strtol for example:

       char *p = strtok(b," ");
        while( p != NULL)
        {
           arr[i++] = strtol(p, NULL, 10); // arr[i++] = p is wrong, because p is a string not an integer value
           p = strtok(NULL," ");
        }
    

    When you print the value of array, use %d for integer value instead of %s. You use init_size is wrong. Because in the string, it has some space character. Your printing part should change to:

        for(int j = 0; j < i; j++)
            printf("%d\n", arr[j]);
    

    The complete code:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char b[] = "1 2 3 4 5";
        int init_size = strlen(b);
        int arr[init_size];
        int i = 0;
    
        char *p = strtok(b," ");
        while( p != NULL)
        {
           arr[i++] = strtol(p, NULL, 10);
           p = strtok(NULL," ");
        }
    
        for(int j = 0; j < i; j++)
            printf("%d\n", arr[j]);
    
    return 0;
    }