C Program To Split a String Into Words
In this tutorial, we are going to see how to write a C program to split a string into words using strtok() function. To split a string, we need a delimiter – a delimiter is a character that will be used to split the string.
Let’s say we have the following string and we want to extract each word from the string.
char str[] = "Welcome to StackHowTo best online learning platform";
Notice that the words are separated by a space. So the space will be our delimiter in this case.
char delimiter[] = " ";
strtok() function accepts two parameters – the first is the string to be split, the second is the delimiter. The strtok function returns a pointer to the character of the next word.
char *p = strtok(str, delimiter);
[st_adsense]
C Program To Split a String Into Words
#include <stdio.h> #include <string.h> int main() { char str[] = "Welcome to StackHowTo best online learning platform"; int len = strlen(str); char delimiter[] = " "; char *p = strtok(str, delimiter); while(p != NULL) { printf("'%s'\n", p); p = strtok(NULL, delimiter); } printf("\n"); return 0; }
Output:
'Welcome' 'to' 'StackHowTo' 'best' 'online' 'learning' 'platform'
[st_adsense]