Reputation: 163
To loop over a string str I used:
for (tok = strtok(str, ";"); tok && *tok; tok = strtok(NULL, ";"))
{
//do stuff
}
I would like to understand how this loop works. It seems to me:
(1) tok = strtok(str, ";"); //initialization of tok with the first token in str
(2) tok = strtok(NULL, ";"); // go to the next token in str? how does this work?
(3) tok && *tok; //this stops the loop when tok =NULL or *tok=NULL
I would appreciate your help!
Upvotes: 7
Views: 4848
Reputation: 22925
Here's a sample strtok implementation: http://bxr.su/o/lib/libc/string/strtok.c#strtok
As you see in the code, it uses a static character pointer internally (pretty much every version I've seen store a pointer, either as a global variable or as a static variable as in the case above). This version calls the reentrant strtok_r
(and the side effect of the line if (s == NULL && (s = *last) == NULL)
is to use the last pointer if NULL is passed)
Upvotes: 4
Reputation: 27802
You can find more about strtok here. It has some examples of how to use it.
Quoting from the link, the str
parameter in strtok(str, delim)
:
Notice that the contents of this string are modified and broken into smaller strings (tokens). Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
Your 3 guesses are correct.
Upvotes: -1
Reputation: 83557
(2) tok = strtok(NULL, ";"); // go to the next token in str? how does this work?
That's exactly how strtok()
works. By sending NULL
as the first parameter, you signal that strtok()
should continue with the string which was sent to it during the last call. If you want to know the exact implementation details, you will need to look at the source code for strtok()
. Most likely it uses a static local variable.
Upvotes: 1
Reputation: 13535
if you read the manpages
for strtok
it states
The strtok() function parses a string into a sequence of tokens. On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.
Upvotes: -1