strtok() function is part of the
The syntax of the strtok() function is as follows −
char* strtok(char* string, const char* limiter);
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.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; }
When the above program is executed, it produces the following results −
Token List: Hello Tutorials Point!
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!