Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strtok() in nested loops in C?

Tags:

c

string

strtok

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, "%");
}
like image 558
Alex Xander Avatar asked Oct 02 '09 13:10

Alex Xander


People also ask

What is the purpose of strtok () function?

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.

What is strtok used for in C?

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.

Can strtok be used with 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 .

How is strtok implemented?

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.


2 Answers

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" */
}
like image 152
Alex B Avatar answered Sep 20 '22 15:09

Alex B


strtok is using a static buffer. In your case you should use strtok_r. This function is using a buffer provided by the user.

like image 32
Patrice Bernassola Avatar answered Sep 20 '22 15:09

Patrice Bernassola