Use strtok in a for loop

To iterate over the str string that I used:

for (tok = strtok(str, ";"); tok && *tok; tok = strtok(NULL, ";")) { //do stuff } 

I would like to understand how this cycle works. I think:

 (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 be grateful for your help!

+6
source share
4 answers

Here is an example strtok implementation: http://bxr.su/o/lib/libc/string/strtok.c#strtok

As you can see in the code, it uses a static pointer to a character inside (almost every version I saw stores 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 if (s == NULL && (s = *last) == NULL) line if (s == NULL && (s = *last) == NULL) is to use the last pointer if NULL is passed)

+4
source

(2) tok = strtok (NULL, ";"); // move to the next token in str? how it works?

This is how strtok() works. By sending NULL as the first parameter, you signal that strtok() should continue the line that was sent to it during the last call. If you want to know the exact implementation information, you will need to look at the source code for strtok() . Most likely it uses a static local variable.

+1
source

if you read manpages for strtok , it points

The strtok () function parses a string in a sequence of tokens. On the first call to strtok (), the string to be parsed must be defined. on the street In each subsequent call that must parse the same string, str must be NULL.

-1
source

Here you can find more information about strtok . It has several examples of how to use it.

Quote from the link, str parameter in strtok(str, delim) :

Please note that the contents of this line are changed and broken up into smaller lines (tokens). Alternatively, a null pointer may be specified, in which case the function continues to scan where the previous successful function call ended.

Your 3 assumptions are correct.

-1
source

Source: https://habr.com/ru/post/948281/


All Articles