Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use strtok in a for loop

Tags:

c

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!

like image 312
loisir1976 Avatar asked Jun 27 '13 23:06

loisir1976


People also ask

How do I use strtok ()?

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.

How do I use strtok in C++?

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.

What can I use instead of strtok in C?

Use strtok_r(). It's the same behaviour as strtok, but allow you to work with multiple strings "simultaneously".

Can strtok be used with threads?

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.


2 Answers

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)

like image 117
SheetJS Avatar answered Sep 19 '22 15:09

SheetJS


(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.

like image 40
Code-Apprentice Avatar answered Sep 20 '22 15:09

Code-Apprentice