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!
The strtok function is used to tokenize a string and thus separates it into multiple strings divided by a delimiter. The first call to strtok returns the pointer to the first substring. All the next calls with the first argument being NULL use the string passed at the first call and return the next substring.
The syntax of strtok() is: strtok(char* str, const char* delim); In simple terms, str - the string from which we want to get the tokens.
Use strtok_r(). It's the same behaviour as strtok, but allow you to work with multiple strings "simultaneously".
Every call to the strtok() function, returns a refrence to a NULL terminated string and it uses a static buffer during parsing. Any subsequent call to the function will refer to that buffer only, and it gets altered.! It is independent of who called it, and thats is the reason for it is not thread safe.
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)
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With