Thursday, 20 March 2014

Strtok Function in C

    string s;
    getline(cin,s);
    char *pch;
    char str[10000];
    // you s.c_str() returns a const char * pointer you can not directly cast to char *, Hence char * str=s.c_str() will give you compilation error, Hence allocate the memory for str first and then use strcpy function to copy the constant string into the memory.
    strcpy(str,s.c_str());
 
    pch=strtok(str,"-");
    // gives you the first token, if it is NULL, all the characters in the string were from delimeters.
    while(pch!=NULL)
    {
        printf("HI%sHI\n",pch);
        // in the subsequent calls, always pass NULL.
        pch=strtok(NULL,"-");
    }
 
    // note that str is getting changed by the the strtok function.

You can also do the same thing in this way too.
vector split(string s, string del = " ") { char *word, *buf, *delim; vector res; delim = strdup(del.c_str()); buf = strdup(s.c_str()); for (word = strtok(buf, delim); word; word = strtok(0, delim)) res.push_back(string(word)); free(buf); free(delim); return res; }

strdup can also be used instead of strcpy, but you should never forget to free the memory, though most of time not necessary in contests.

Refereneces 
http://www.cplusplus.com/reference/cstring/strtok/
http://apps.topcoder.com/forums/?module=Thread&threadID=672251&start=0