strtok 指针采用分隔符值

strtok pointer takes delimeter value

我想用多个分隔符测试 strtok,我写了下面的代码,但是在打印第一个标记后,标记采用分隔符值而不是字符串中下一个单词的值。

#include <string.h>

int main(int argc, char *argv[]) {
    char sent[]="-This is ?a sentence, with various symbols. I will use strtok to get;;; each word.";
    char *token;
    printf("%s\n",sent);
    token=strtok(sent," -.?;,");
    while(token!=NULL){
        printf("%s\n",token);
        token=(NULL," -.?;,");
    }
    return 0;
}

如果您打算在循环中调用 strtok,每次将下一个标记拉入字符串,则更改此行:

 token=(NULL," -.?;,");//this syntax results in token being pointed to
                       //each comma separated value within the
                       //parenthesis from left to right one at a time.
                       //The last value, in this case " -.?;,", is what
                       //token finally points to.

 token=strtok(NULL, " -.?;,");

您不要在循环中再次调用 strtok:

token=(NULL," -.?;,");

这可以编译,因为您在这里使用了逗号运算符。 NULL 表达式被丢弃,表达式产生“-.?;,令牌指向它。

改为

token=strtok(NULL," -.?;,");

在此处阅读有关逗号运算符的更多信息:

What does the comma operator , do?