I needed to know when there was no data between two delimiters so I found the following code on Stack Overflow.
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;
}
Sampling the function
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);
}
Output
foo
bar
<empty>
baz
biz
<empty>
// missing another <empty>
With the current code, it does not process data after the last ',' There should be one more empty field. I am unsure how to get the correct output.