strtok指针占用分隔值

时间:2017-05-16 12:55:21

标签: c strtok

我想测试带有多个分隔符的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;
}

2 个答案:

答案 0 :(得分:4)

如果您打算在循环中调用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, " -.?;,");

答案 1 :(得分:2)

你不会再次在循环中调用strtok:

as.data.frame(t(sapply(seq(1,(nrow(df)-1),2),function(x,df){df[x,]/df[x+1,]},df)))

这个编译是因为你在这里使用逗号运算符。 NULL表达式被丢弃,表达式产生“ - 。?;,并且令牌指向那个。

将其更改为

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

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

What does the comma operator , do?