如何使"strtok function"一次使用多个令牌字符串? 函数指针会解决这个问题吗?



strtok函数使用一个静态变量将字符串解析为令牌。因此,当执行多个调用时,这会导致冲突。除了使用线程,我还能做以下事情吗:thx
-我可以使用函数指针在两个不同的位置分配函数吗?这会使"strtok"中的静态变量分配在两个不同的位置吗?

//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);
}

使用strtok_r()(重入版本)。

也许可以使用strsep而不是使用strtok。请注意,我已经将嵌套循环提取为一个函数——嵌套循环太糟糕了!

已编辑:更改为直接使用strsep

/* print each word in a string*/
static void print_words(char *s)
{
    while (s && *s) {
        char *t = strsep(&s, " ");
        printf("WORD:  %sn", 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:  %sn", s);
        print_words(s);
    }
}

使用strtok_r()。它还需要一个类似上下文的参数指针。

那是C还是C++?

如果是C++,则可以使用std::string而不是char *std::string方法来获得与使用strtok相同的结果。

例如,您可以从findsubstr方法中获得好处。

相关内容

最新更新