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
// C program for splitting a string // using strtok() #include <stdio.h> #include <string.h> int main()
{ char str[] = "Geeks-for-Geeks" ;
// Returns first token
char * token = strtok (str, "-" );
// Keep printing tokens while one of the
// delimiters present in str[].
while (token != NULL) {
printf ( "%s" , token);
token = strtok (NULL, "-" );
}
return 0;
} |
Output: Geeks for Geeks