2
 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 ?

Kundan Kumar
  • 1,974
  • 7
  • 32
  • 54
  • 1
    Possible duplicate: http://stackoverflow.com/questions/8977836/strtok-s-behaviour-with-consecutive-delimiters - although the answers here are better. – Csq Jan 16 '13 at 09:11

2 Answers2

5

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

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