The strtok
function has an internal state that remembers the last position which it has reached. Since it overwrites the original string by replacing the token with zero, all it needs to remember is the next position in the string. If you call strtok
with a non-null string argument, the internal state is reset to the new string. So indeed, you cannot use it on multiple strings at once, only one after the other. (Some platforms provide the reentrant variant strtok_r
which allows you to pass your own state variable.)
Here's a sample implementation:
char * my_strtok(char * in, char delim) // not quite the same signature
{
_Thread_local static char * pos = NULL;
if (in) { pos = in; }
char * p = find_next_delimiter(pos, delim); // NULL if not found
if (p) { *p = '\0'; ++p; pos = p; }
return p;
}
(The real strtok
searches for any delimiter of a given list, and also skips over empty fields.) The reentrant variant of this would replace the static variable pos
with a function parameter.