To understand how strtok() works, you first need to know what a static variable is . This link explains it pretty well ....
The key to the strtok() operation is to save the location of the last separator between secret calls (therefore, strtok() continues parsing the original string itself, which is passed to it when it is called using the null pointer in successive calls).
Take a look at my own implementation of strtok() called zStrtok() , which has poor functionality than the one provided by strtok()
char *zStrtok(char *str, const char *delim) { static char *static_str=0; int index=0, strlength=0; int found = 0; if (delim==0 || (str == 0 && static_str == 0)) return 0; if (str == 0) str = static_str; while(str[strlength]) strlength++; for (index=0;index<strlength;index++) if (str[index]==delim[0]) { found=1; break; } if (!found) { static_str = 0; return str; } if (str[0]==delim[0]) { static_str = (str + 1); return (char *)delim; } str[index] = '\0'; if ((str + index + 1)!=0) static_str = (str + index + 1); else static_str = 0; return str; }
And here is a usage example
Example Usage char str[] = "A,B,,,C"; printf("1 %s\n",zStrtok(s,",")); printf("2 %s\n",zStrtok(NULL,",")); printf("3 %s\n",zStrtok(NULL,",")); printf("4 %s\n",zStrtok(NULL,",")); printf("5 %s\n",zStrtok(NULL,",")); printf("6 %s\n",zStrtok(NULL,",")); Example Output 1 A 2 B 3 , 4 , 5 C 6 (null)
The code from the string processing library that I support on Github is called zString. Look at the code or even contribute :) https://github.com/fnoyanisi/zString