strtok behavior

99封情书 提交于 2019-12-02 07:27:43

问题


 int main ()
 {

    char str[] ="kk,12,,23,4,,,3434,3,33,,,";
    char * valarr;
    int count=0;
    valarr = strtok(str,","); 
    while(valarr != '\0')
    {
               valarr = strtok(NULL,","); 
    count++;
    }
    printf("%d\n",count);
   return 0;
  }

In above program the output is 7.

It seems that the strtok is tokenizing consecutive commas at once.

Instead of consecutive commas I can introduce a blank in between but Is there a way to overcome this so that I have empty space also in the count ?


回答1:


Correct. The documentation states this pretty clearly:

A sequence of two or more contiguous delimiter characters in the parsed string is considered to be a single delimiter.

That's just how strtok() is supposed to work. You might be better of rolling your own, which will also free you from strtok()'s nastiness.




回答2:


Short answer: NO At least using strtok, check this to learn what's better for your application.



来源:https://stackoverflow.com/questions/14354622/strtok-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!