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.
The general syntax for the strtok()
function is:
char *strtok(char *str, const char *delim)
Let’s look at the parameters the strtok()
function takes as input:
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.
Let’s start off by a simple example!
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; }
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
View all Courses