tags:

views:

155

answers:

5
          char *token = "gkjsdhvcxvcvbcbcv"            
          char c[90];  
          strcpy( c, token);
          c[sizeof(c)-1] = '\0';
          char *broken = strtok(c, " ");                 
          if ( broken != NULL)
          {  
            //Should not come here as there is no white space???
           }
+3  A: 

The string itself, in the absence of delimiters, is the first token.

If you try to print broken, I think you'll see this is the case.

If you want to have a section of code not executed when a string lacks a particular character, you should test with strstr or strchr instead.

Welbog
+14  A: 

You're getting the first token which is the entire string. A second call would return NULL as there are no more tokens:

char *token = "gkjsdhvcxvcvbcbcv"            
char c[90];  
strcpy( c, token);
c[sizeof(c)-1] = '\0';
char *broken = strtok(c, " ");                 
if ( broken != NULL) {  
    // Will come in here, broken == c.
}
broken = strtok(NULL, " ");                 
if ( broken != NULL) {  
    // Won't come in here.
}
paxdiablo
+3  A: 

strtok divides the input string into smaller strings split by the input delimiters. Since there is no white space, it returns the whole string.

erelender
A: 

Things that could go wrong with the above code:

  • not using at least strncpy is asking for problems, eventually
  • What is sizeof(c) returning? I forgot at the moment, but my guesses are either 1, or 90. (probably 90)

And as other have pointed out, strtok() seems to be behaving properly.

Calyth
@ Calyth: First point was discuss here : http://stackoverflow.com/questions/1508838/how-to-copy-char-str-to-char-c-in-c. Second point: sizeof(c) is returning 90 where strlen is returning number of character in char* (discuss too in the other thread)
Patrice Bernassola
Yeah, I saw the similar post. I never like the sizeof(c) where c is a char[] syntax. Someone wrote a macro for the length of an array based on that, and it gets very confusing if you accidentally pass a char* instead.
Calyth
+3  A: 

Are you trying to determine whether or not the string has spaces in it?

If so, then the solution is to use strchr() instead of strtok(). e.g.

if (strchr(c, ' ') == NULL) {
    // string has no spaces
} else {
    // string has at least one space
}

If you want to tokenize the string only if the string contains at least one delimiter, then you need to use both strchr() & strtok():

char *broken = NULL;
if (strchr(c, ' ') != NULL)
    broken = strtok(c, " ");
Ferruccio