I am trying to use strtok()
in nested loops but this is not giving me desired results,
possibly because they are using the same memory location. My code is of the form:-
char *token1 = strtok(Str1, "%");
while (token1 != NULL)
{
char *token2 = strtok(Str2, "%");
while (token2 != NULL)
{
//Do something
token2 = strtok(NULL, "%");
}
// Do something more
token1 = strtok(NULL, "%");
}
The strtok() function reads string1 as a series of zero or more tokens, and string2 as the set of characters serving as delimiters of the tokens in string1. The tokens in string1 can be separated by one or more of the delimiters from string2.
In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.
strtok() splits a string ( string ) into smaller strings (tokens), with each token being delimited by any character from token . That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token .
The strtok() function is used in tokenizing a string based on a delimiter. It is present in the header file “string. h” and returns a pointer to the next token if present, if the next token is not present it returns NULL. To get all the tokens the idea is to call this function in a loop.
Yes, strtok()
, indeed, uses some static memory to save its context between invocations. Use a reentrant version of strtok()
, strtok_r()
instead, or strtok_s()
if you are using VS (identical to strtok_r()
).
It has an additional context argument, and you can use different contexts in different loops.
char *tok, *saved;
for (tok = strtok_r(str, "%", &saved); tok; tok = strtok_r(NULL, "%", &saved))
{
/* Do something with "tok" */
}
strtok is using a static buffer. In your case you should use strtok_r. This function is using a buffer provided by the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With