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???
}
views:
155answers:
5The 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.
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.
}
strtok divides the input string into smaller strings split by the input delimiters. Since there is no white space, it returns the whole string.
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.
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, " ");