I stumbled upon a question on SO asking how to split a comma-separated string into individual values.
Since it's been a while since I've had any good reason to write C I'd like to ask for some feedback.
#include <stdio.h>
#include <string.h>
int main (int argc, const char * argv[]) {
const char str[] ="coma separated,input,,,some fields,,empty";
const char tok[] = ",";
char * tmp = (char *)str;
size_t count;
for (count=0; tmp[count]; tmp[count] == tok[0] ? count++ : * tmp++) {
//Empty loop body.
}
tmp = (char *)str;
for (size_t i = 0, l = 0; i < count; i++) {
l = strcspn (tmp, tok);
if (l == 0) {
printf("\"\"\n");
} else {
printf("\"%.*s\"\n", l, tmp);
}
tmp += sizeof(char) * (l + 1);
}
printf("\"%s\"\n", tmp);
return 0;
}
Output as expected:
"coma separated"
"input"
""
""
"some fields"
""
"empty"
,
and"
values? en.wikipedia.org/wiki/Comma-separated_values \$\endgroup\$