Split string into tokens and save them in an array

Syeda Amna Ahmed picture Syeda Amna Ahmed · Mar 18, 2013 · Viewed 137.2k times · Source

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

Answer

rlib picture rlib · Mar 18, 2013
#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;
}