#include <stdio.h>
#include <string.h>
char * mystrtok(char *, char *);
int main ()
{
char str[] = "one";//Yellow fox jumps over the lazy dog";
char *delim = " ";
char *token;
/* get the first token */
token = mystrtok(str, delim);
/* iterate through other tokens */
while(token)
{
printf( "\n%s", token );
token = mystrtok(NULL, delim);
}
return 0;
}
char * mystrtok(char * src, char * delim)
{
static char * mystr = 0;
char * pos;
if(src)
{ /*The function was called for the first time: set the static variable and return first token*/
mystr = src;
if(pos = strstr(mystr, delim))
{
*pos = '\0';
mystr = ++pos;
return src;
}
/*This part of the code is executed when the last token is reached.
Return it and set static pointer to zero to finish it off*/
src = mystr;
mystr = 0;
return src;
}
else
{ /*Function is called second and consecutive times. Reuse the logic by calling itself with substituted first parameter*/
return (mystr ? mystrtok(mystr, delim) : 0);
}
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdHJpbmcuaD4KCmNoYXIgKiBteXN0cnRvayhjaGFyICosIGNoYXIgKik7CgppbnQgbWFpbiAoKSAKewogICBjaGFyIHN0cltdID0gIm9uZSI7Ly9ZZWxsb3cgZm94IGp1bXBzIG92ZXIgdGhlIGxhenkgZG9nIjsKICAgY2hhciAqZGVsaW0gPSAiICI7CiAgIGNoYXIgKnRva2VuOwogICAKICAgLyogZ2V0IHRoZSBmaXJzdCB0b2tlbiAqLwogICB0b2tlbiA9IG15c3RydG9rKHN0ciwgZGVsaW0pOwoKICAgLyogaXRlcmF0ZSB0aHJvdWdoIG90aGVyIHRva2VucyAqLwogICB3aGlsZSh0b2tlbikgCiAgIHsKICAgICAgcHJpbnRmKCAiXG4lcyIsIHRva2VuICk7CiAgICAgIHRva2VuID0gbXlzdHJ0b2soTlVMTCwgZGVsaW0pOwogICB9CiAgIAogICByZXR1cm4gMDsKfQoKY2hhciAqIG15c3RydG9rKGNoYXIgKiBzcmMsIGNoYXIgKiBkZWxpbSkKewogICAgc3RhdGljIGNoYXIgKiBteXN0ciA9IDA7IAogICAgY2hhciAqIHBvczsKCiAgIC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