C Program to Split a String into a Number of Sub-Strings
Last Updated :
26 Oct, 2022
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array.Â
Almost all programming languages, provide a function split a string by some delimiter.Â
In C:Â Â
// Splits str[] according to given delimiters.
// and returns next token. It needs to be called
// in a loop to get all tokens. It returns NULL
// when there are no more tokens.
char * strtok(char str[], const char *delims);
C
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Geeks-for-Geeks" ;
char * token = strtok (str, "-" );
while (token != NULL) {
printf ( "%s" , token);
token = strtok (NULL, "-" );
}
return 0;
}
|
Output: Geeks
for
Geeks
Share your thoughts in the comments
Please Login to comment...