String tokenisation function in C


In this section, we will see how to tokenize strings in C. The C has library function for this. The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim.

Following is the declaration for strtok() function.

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

It takes two parameters. The str - The contents of this string are modified and broken into smaller strings (tokens), and delim - This is the C string containing the delimiters. These may vary from one call to another. 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 Code

 Live Demo

#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
", token );       token = strtok(NULL, s);    }    return(0); }

Output

This is
www.tutorialspoint.com
website

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements