Home > Backend Development > C++ > 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.

王林
Release: 2023-08-26 09:45:11
forward
2119 people have browsed it

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);
Copy after login

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;
}
Copy after login

Output

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

Token List:
Hello
Tutorials
Point
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template