Is there a way to count tokens in C?

前端 未结 3 1631
遥遥无期
遥遥无期 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:07

    Here is a version based on strtok which does not modify the original string, but a temporal copy of it. This version works for any combination of tabs and space characters used as tokens separators. The function is

    unsigned long int getNofTokens(const char* string){
      char* stringCopy;
      unsigned long int stringLength;
      unsigned long int count = 0;
    
      stringLength = (unsigned)strlen(string);
      stringCopy = malloc((stringLength+1)*sizeof(char));
      strcpy(stringCopy,string);
    
      if( strtok(stringCopy, " \t") != NULL){
        count++;
        while( strtok(NULL," \t") != NULL )
            count++;
      }
    
      free(stringCopy);
      return count;
    }
    

    A function call could be

    char stringExample[]=" wordA 25.4 \t 5.6e-3\t\twordB 4.5e005\t ";
    printf("number of elements in stringExample is %lu",getNofTokens(stringExample));
    

    Output is

    number of elements in stringExample is 5
    

提交回复
热议问题