jdl
jdl

Reputation: 6323

How to make "strtok function" work with more than one Token String at a time? Would function pointers solve this?

strtok function uses a static variable for parsing the string into tokens. So this causes a conflict when multiple calls are done. Other than using threads how could I do the following: thx
- Can I use a function pointer to allocate the function at 2 different places? Would this make the static variable inside "strtok" allocate at 2 different places?

//breaking up first by Sentence and than by Word.
char phrase[] = "My dog has fleas.\nAnd he gave them to me."; 
char del1[]   = "\n";
char del2[]   = " ";
char *token1;
char *token2;


token1 = strtok( phrase, del1);

while( token1 != NULL )
{
    printf("Sentence:  %s",token1);

    token2 = strtok( token1, del2);
    while( token2 != NULL ){
        token2 = strtok( NULL, del2);
        printf("WORD:  %s",token2);
    }

    token1 = strtok( NULL, del1);
}

Upvotes: 0

Views: 2173

Answers (4)

William Morris
William Morris

Reputation: 3684

Instead of using strtok, perhaps use strsep. Note that I have extracted the nested loop into a function - nested loops suck!

EDITED: changed to use strsep directly

/* print each word in a string*/
static void print_words(char *s)
{
    while (s && *s) {
        char *t = strsep(&s, " ");
        printf("WORD:  %s\n", t);
    }
}

void loop(void)
{
    /* duplicate string in case it is read-only */
    char *phrase = strdup("My dog has flees.\nAnd he gave them to me.");

    while (phrase) {
        char *s = strsep(&phrase, "\n");
        printf("Sentence:  %s\n", s);
        print_words(s);
    }
}

Upvotes: 2

Vincenzo Pii
Vincenzo Pii

Reputation: 19805

Is that C or C++?

If it is C++, you can use std::string instead of char * and std::string methods to achieve the same result as you get using strtok.

For example you could get benefits from find and substr methods.

Upvotes: 1

Vadym S. Khondar
Vadym S. Khondar

Reputation: 1438

Use strtok_r(). It takes one more parameter - pointer which acts like a context.

Upvotes: 1

P.P
P.P

Reputation: 121397

use strtok_r() (re-entrant version).

Upvotes: 6

Related Questions