Home > Backend Development > C++ > What is strtok() function in C language?

What is strtok() function in C language?

王林
Release: 2023-08-28 23:29:06
forward
1576 people have browsed it

What is strtok() function in C language?

strtok() function is part of the header file #include

The syntax of the strtok() function is as follows −

char* strtok(char* string, const char* limiter);
Copy after login

Enter a string and a delimiter character limiter. strtok() will split the string into tokens based on the delimiting character.

We can expect to get a list of strings from strtok(). However, the function returns a separate string because after calling strtok(input, limiter) it returns the first token.

But we have to call the function on an empty input string again and again until we get NULL!

Normally, we would keep calling strtok(NULL, delim) until it returns NULL.

Example

The following is the strtok() function of the C programExample:

Online demonstration

#include <stdio.h>
#include <string.h>
int main() {
   char input_string[] = "Hello Tutorials Point!";
   char token_list[20][20];
   char* token = strtok(input_string, " ");
   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(NULL, " "); // Get the next token. Notice that input=NULL now!
   }
   // 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, it produces the following results −

Token List:
Hello
Tutorials
Point!
Copy after login

The input string is "Hello Tutorials Point", and we try to segment it by spaces.

We get the first token by using strtok(input, " "). Here the double quotes are the delimiter, which is a single character string!

After that, we continue to get the tag by using strtok(NULL, " ") and loop until we get NULL from strtok().

The above is the detailed content of What is strtok() function in C language?. For more information, please follow other related articles on the PHP Chinese website!

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