csplitstrtok

Split string into tokens and save them in an array


How to split a string into an tokens and then save them in an array?

Specifically, I have a string "abc/qwe/jkh". I want to separate "/", and then save the tokens into an array.

Output will be such that

array[0] = "abc"
array[1] = "qwe"
array[2] = "jkh"

please help me


Solution

  • #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
        char buf[] ="abc/qwe/ccd";
        int i = 0;
        char *p = strtok (buf, "/");
        char *array[3];
    
        while (p != NULL)
        {
            array[i++] = p;
            p = strtok (NULL, "/");
        }
    
        for (i = 0; i < 3; ++i) 
            printf("%s\n", array[i]);
    
        return 0;
    }