Search code examples
cstrtok

strtok pointer takes delimeter value


I wanted to test strtok with multiple delimeters, and I wrote the code below, but after printing the first token, token takes the delimeter value instead that of the next word in the string.

#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;
}

Solution

  • If your intent is to call strtok in a loop, each time pulling the next token into a string, then change this line:

     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.
    

    to

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