Is there a way to count tokens in C?

前端 未结 3 1627
遥遥无期
遥遥无期 2021-02-08 08:00

I\'m using strtok to split a string into tokens. Does anyone know any function which actually counts the number of tokens?

I have a command string and I nee

3条回答
  •  孤城傲影
    2021-02-08 08:04

    One approach would be to simply use strtok with a counter. However, that will modify the original string.

    Another approach is to use strchr in a loop, like so:

    int count = 0;
    char *ptr = s;
    while((ptr = strchr(ptr, ' ')) != NULL) {
        count++;
        ptr++;
    }
    

    If you have multiple delimiters, use strpbrk:

    while((ptr = strpbrk(ptr, " \t")) != NULL) ...
    

提交回复
热议问题