strtok() : Split string into tokens
Syntax :
char * strtok ( char * str, const char * delimiters );
Parameters
str C string to truncate.Notice that this string is modified by being 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.
delimiters C string containing the delimiter characters. These can be different from one call to another.
Example
-
/* strtok example */ #include <stdio.h> #include <string.h> int main (){ char str[] ="- This, a sample string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str," ,.-"); while (pch != NULL){ printf ("%s\n",pch); pch = strtok (NULL, " ,.-"); } return 0; }
code courtesy : cplusplus.com
Why Function strtok()
is not Thread Safe / reentrant
The strtok()
function uses a intermediate static buffer while parsing, and reuse them at each call so it’s not thread safe.
Solution :
Use strtok_r()
to use strtok as thread safe