C library - strtok() function



The C Library strtok() function is used for tokenizing strings. These strings are a set of tokens using delimiters/separators characters. In general, tokens are usually words, phrases, or individual characters within a string.

Here, char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim.

Syntax

Following is the syntax of the C library strtok() function −

char *strtok(char *str, const char *delim)

Parameters

This funtion accepts the following parameter −

  • str − The contents of this string are modified and broken into smaller strings(tokens).

  • delim − This is the C string containing the delimiters. These may vary from one call to another.

Return Value

This function returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve.

Example 1

Following is the C program that illustrates the usage of strtok() function.

#include <string.h>
#include <stdio.h>

int main () {
   char str[80] = "This is - www.tutorialspoint.com - website";
   const char s[2] = "-";
   char *token;
   
   /* get the first token */
   token = strtok(str, s);
   
   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token );
    
      token = strtok(NULL, s);
   }
   
   return(0);
}

Output

On execution of above code, we get the following result −

This is 
  www.tutorialspoint.com 
  website

Example 2

In this example, we demonstrates each substring of the string is represented in a new line using strtok() function.

#include <stdio.h>
#include <string.h>

int main() {
   char stng[100] = "Welcome to C Programming";
   char *res;
   
   res = strtok(stng, " ");
   while(res != NULL) {
      printf("%s \n", res);
      res = strtok(NULL, " ");
   }
   return 0;
}

Output

After executing the above code, the outcome becomes −

Welcome 
to 
C 
Programming 

Example 3

Following is the C program that demonstrates how to returns the null pointer using strtok() function.

#include <stdio.h>
#include <string.h>
int main()
{
   //String i.e. break in token
   char str_1[] = "ttttt";
   
   //delimiter
   char *str_2 = "tp";
   
   // initial call of strtok
   char *token = strtok(str_1, str_2);
   
   printf("The resultant token is %s\n", token);
   return 0;
}

Output

The above code produces the following result −

The resultant token is (null)
Advertisements