This function is similar to the strtok() function. The only key difference is that the _r, which is called as re-entrant function.
A re-entrant function is a function which can be interrupted during its execution. This type of function can be used to resume execution.
Because of this fact, re-entrant functions are thread-safe, means they can safely be interrupted by threads without any harm.
strtok_r() function has an extra parameter called the context. so that function can resume at the right place.
The syntax for strtok_r() function is as follows:
#include <string.h> char *strtok_r(char *string, const char *limiter, char **context);
Example
Following is the C program for the use of strtok_r() function −
#include <stdio.h> #include <string.h> int main(){ char input_string[] = "Hello Tutorials Point"; char token_list[20][20]; char* context = NULL; char* token = strtok_r(input_string, " ", &context); int num_tokens = 0; // Index to token list. We will append to the list while (token != NULL){ strcpy(token_list[num_tokens], token); // Copy to token list num_tokens++; token = strtok_r(NULL, " ", &context); } // Print the list of tokens printf("Token List:\n"); for (int i=0; i < num_tokens; i++) { printf("%s\n", token_list[i]); } return 0; }
Output
When the above program is executed, it produces the following result −
Token List: Hello Tutorials Point