What is strtok() function in C language?


strtok() function is a part of the <string.h> header file #include <string.h>

The syntax of strtok() function is as follows −

char* strtok(char* string, const char* limiter);

Input string string and a delimiter character limiter. strtok() will divide the string into tokens based on the delimited character.

We can expect a list of strings from strtok(). But, the function returns a single string because after calling strtok(input, limiter), it will returns the first token.

But we have to keep calling the function again and again on a NULL input string, until we get NULL! Generally, we used to keep calling strtok(NULL, delim) until it returns NULL.

Example

Following is the C program for strtok() function

 Live Demo

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

Output

When the above program is executed, it produces the following result −

Token List:
Hello
Tutorials
Point!

Input string is “Hello Tutorials Point”, and we are trying to tokenize it by spaces.

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

Afterwards, we keep getting tokens by using strtok(NULL, " ") and loop until we get NULL from strtok().

Updated on: 03-Sep-2021

905 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements