Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
string split
strtok

Splitting a string using strtok() in C

Educative Answers Team

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

svg viewer

Syntax

The general syntax for the strtok() function is:

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

Parameters

Let’s look at the parameters the strtok() function takes as input:

  • str: The string which is to be split
  • delim: The character on the basis of which the split will be done

Return value

The function performs one split and returns a pointer to the token split up. A null pointer is returned if the string cannot be split.

Example

Let’s start off by a simple example!

1. Extracting a single token

The following piece of code will just split up the Hello world string in two and will return the first token extracted from the function.

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

int main() {
   char string[50] = "Hello world";
   // Extract the first token
   char * token = strtok(string, " ");
   printf( " %s\n", token ); //printing the token
   return 0;
}

2. Extracting all possible tokens

To find all possible splits of the string, based on a given delimiter, the function needs to be called in a loop. See the example below to see how this works.

Let’s see how we can split up a sentence on each occurrence of the white space character:

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

int main() {
   char string[50] = "Hello! We are learning about strtok";
   // Extract the first token
   char * token = strtok(string, " ");
   // loop through the string to extract all other tokens
   while( token != NULL ) {
      printf( " %s\n", token ); //printing each token
      token = strtok(NULL, " ");
   }
   return 0;
}

RELATED TAGS

c
string split
strtok
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses