Thursday, 20 March 2014

Strtok Function in C

    string 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.
    // gives you the first token, if it is NULL, all the characters in the string were from delimeters.
        // in the subsequent calls, always pass 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.


No comments:

Post a Comment