1
pch = strtok(str," ");
strcpy(piece1,pch);
printf("\n piece1 : %s \n",piece1);
while(pch != NULL){
        printf("\n %s \n",pch);
        pch = strtok(NULL," ");
        if(pch != NULL){
                strcpy(piece2,pch);
                printf("\n piece2 : %s \n",piece2);
        }
}

strtok(str, " ")用 .填充字符串中的空间'\0'。做什么strtok(NULL, " ")?获得第一个令牌后如何拆分剩余的字符串。

4

1 回答 1

3

strtok does some things that could be perceived of as dangerous. Namely, when you call it and the first argument isn't NULL, it saves that argument and some other information in static variables (making it completely thread UNsafe).

As long as you keep passing null, it uses the same char array you originally passed it to look for more tokens.

Actually, more likely the implementation is that it saves the place it was in your string in a static variable. It shouldn't care about where your string began; it only cares about where it is in your string.

Also, remember that strtok is changing the actual string you pass it, so if you needed that string to not have a bunch of '\0's in it, you should have made a copy of it before invoking strtok.

于 2013-09-26T16:50:29.347 回答