7.21.5.8 strtok function
The standard says strtok :
[# 3] The first call in the sequence looks for a string pointed to by s1 for the first character that is not contained in the current line of the separator pointed to by s2 . If such a symbol is not found, then there are no tokens in it. the string pointed to by s1 , and the strtok returns a null pointer. If such a symbol is found, this is the beginning of the first token.
In the above quote, we can read that you cannot use strtok as a solution to your specific problem, as it will treat any consecutive characters found in delims as a single token.
Am I doomed to cry in silence, or can someone help me?
You can easily implement your own version of strtok that does what you want, see the snippets at the end of this post.
strtok_single uses strpbrk (char const* src, const char* delims) , which will return a pointer to the first occurrence of any character in the dividends that is in the line with the terminating src zero.
If no matching character is found, the function will return NULL.
strtok_single
char * strtok_single (char * str, char const * delims) { static char * src = NULL; char * p, * ret = 0; if (str != NULL) src = str; if (src == NULL) return NULL; if ((p = strpbrk (src, delims)) != NULL) { *p = 0; ret = src; src = ++p; } else if (*src) { ret = src; src = NULL; } return ret; }
use of example
char delims[] = ","; char data [] = "foo,bar,,baz,biz"; char * p = strtok_single (data, delims); while (p) { printf ("%s\n", *p ? p : "<empty>"); p = strtok_single (NULL, delims); }
Exit
foo bar <empty> baz biz