strtok
The strtok function is used to find a sequence of character strings (tokens) contained in a source string. The sequence of strings must be separated by a character that is passed as a parameter to the function. The strtok function returns only one token per call, therefore for a function that contains several tokens the strtok function needs to be called more than once. In the first call to the function a pointer to a string is required. For additional calls, a value of NULL needs to be passed, since the function saves the original pointer.
The strtok function requires two arguments. The first argument is a pointer to the null terminated character string that is to be divided into tokens. This argument needs to be non-NULL in the first call, and NULL in the subsequent calls to find additional tokens. The second argument is a pointer to a NULL terminated string containing possible separators for the tokens in the original string.
The return value of the strtok function is a pointer to the token that has been found in the current function call. If no token could be found, then the result is NULL.
The following code shows an example of strtok in use:
#include <string.h> #include <stdio.h> int main() { char *o = "the;initial;string"; char s[sizeof(o)+1]; char *tok = 0; strcpy(s, o); do { if (tok) tok = strtok(NULL, ";"); else tok = strtok(s, ";"); if (tok) printf("the token is %s\n", tok); } while (tok); return 0; }
f this string (char s[]) and pass it as the parameter. The output of this code is:
the token is the the token is initial the token is string
Post a comment