Home  >  Article  >  Backend Development  >  The strtok_r() function is a function in C language. Its function is to split a string into a series of substrings.

The strtok_r() function is a function in C language. Its function is to split a string into a series of substrings.

王林
王林forward
2023-08-26 09:45:112110browse

The strtok_r() function is a function in C language. Its function is to split a string into a series of substrings.

This function is similar to the strtok() function. The only key difference is _r, which is called a reentrant function.

A reentrant function is a function that can be interrupted during execution. This type of function can be used to resume execution.

Thus, reentrant functions are thread-safe, which means they can be safely interrupted by threads without causing any damage.

strtok_r() function has an extra parameter called context. This way the function can be restored in the correct location.

The syntax of the strtok_r() function is as follows:

#include <string.h>
char *strtok_r(char *string, const char *limiter, char **context);

Example

The following is a C program using the

strtok_r() function -

Live demonstration

#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:</p><p>");
   for (int i=0; i < num_tokens; i++) {
      printf("%s</p><p>", token_list[i]);
   }
   return 0;
}

Output

When the above program is executed, the following results will be produced-

Token List:
Hello
Tutorials
Point

The above is the detailed content of The strtok_r() function is a function in C language. Its function is to split a string into a series of substrings.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:storm numbersNext article:storm numbers