HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Splitting and printing comma-separated values

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
valuescommasplittingseparatedprintingand

Problem

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 
#include 

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"

Solution

-
sizeof(char) by definition is 1. tmp += l + 1; would be as good.

-
I don't see a need to special case l == 0.

-
You don't have to initialize l in a loop header: it is immediately reassigned.

-
gcc complains about precision specifier in printf("\"%.*s\"\n", l, tmp) being size_t; unfortunately, cast is unavoidable.

-
I don't see a need for 2 separate loops. A single

char * tmp = (char *)str;
do {
    int l = strcspn (tmp, tok);
    printf("\"%.*s\"\n", l, tmp);
    tmp += l + 1;
} while (tmp[-1]);
return 0;


works equally well.

Code Snippets

char * tmp = (char *)str;
do {
    int l = strcspn (tmp, tok);
    printf("\"%.*s\"\n", l, tmp);
    tmp += l + 1;
} while (tmp[-1]);
return 0;

Context

StackExchange Code Review Q#70057, answer score: 7

Revisions (0)

No revisions yet.