strtok() and strtok_r() functions in C with examples
strtok() and strtok_r() functions in C with examples
C offer various strtok() and strtok r() methods for a string to be separated by a certain delimiter. Dividing a string is a simple task. We have a comma-separated number of stuff from a chart, for instance, but we want separate parts in an array.
Parameters
Str: This string's values are changed and split into small strings.
delim: This is the boundary-containing string C. Those can vary from call to call.
Return Value
Its function returns a reference to the first token in the string that was identified. When there are no tokens remaining to retrieve, a null pointer is returned.
strtok()
Example:
The example below demonstrates the usage of the strtok() method.
#include <string.h> #include <stdio.h> int main () { char str[80] = "Hello - www.Tutorialandexample.com"; const char k[2] = "-"; char *token; token = strtok(str, k); /* walk through other tokens */ while( token != NULL ) { printf( " %s\n", token ); token = strtok(NULL, k); } return(0); }
Output:
strtok_r()
Relevant to strtok() in C, strtok r() does the same job of decoding a string into a pattern for tokens. Strtok r() is a re-entered variant of strtok().
There are two ways we can call strtok_r()
A third saveptr argument is a char-pointer * Variable which strtok r() uses internally in Keep context between subsequent calls Parse that same string. Char * strtok r(char * str, * delim, char * * saveptr) const char;
Below is a simple C program displaying when to use strtok r():
// C program to demonstrate working of strtok_r() // by splitting string based on space character. #include <stdio.h> #include <string.h> int main() { char str[] = "Tutorial and example"; char* token; char* rest = str; while ((token = strtok_r(rest, " ", &rest))) printf("%s\n", token); return (0); }
Output:
Another Example of strtok :
// C code to demonstrate working of // strtok #include <stdio.h> #include <string.h> // Driver function int main() { // Declaration of string char gfg[100] = " Tutorial - and - example -"; // Declaration of delimiter const char k[4] = "-"; char* tok; // Use of strtok // get first token tok = strtok(gfg, k); // Checks for delimeter while (tok != 0) { printf(" %s\n", tok); // Use of strtok // go through other tokens tok = strtok(0, k); } return (0); }
Output:
Practical Application
Based on some extractors, strtok could be used to split a string into multiple strings. And use this feature, simple support for CSV files might be implemented. CSV files are delimited with commas.
Example:
// C code to demonstrate the practical application of #include <stdio.h> #include <string.h> // Driver function int main() { char gfg[100] = " 1998 Ford E370 AC 3000."; const char k[4] = " "; char* tok; tok = strtok(gfg, k); while (tok != 0) { printf("%s, ", tok); tok = strtok(0, k); } return (0); }
Output: