file-handling · beginner · ~15 min

Count CSV fields

Tokenise a delimited line by counting separators.

Challenge

Count the comma-separated fields in a CSV line by counting the separators.

Task

Implement int csv_field_count(const char *line) that returns the number of comma-separated fields in line.

Input

line: a NUL-terminated string (one CSV row, no quoting).

Output

Return the field count. An empty string has 0 fields; any non-empty string has (number of commas) + 1.

Example

csv_field_count("a,b,c")   ->   3
csv_field_count("x")       ->   1
csv_field_count("")        ->   0
csv_field_count("a,,b")    ->   3   (the empty middle field counts)

Edge cases

  • Empty string: 0.
  • Consecutive commas produce empty fields that still count.

Input format

line: a CSV row (no quoting).

Output format

int field count: 0 if empty, else commas + 1.

Constraints

Count separators; empty fields still count.

Starter code

int csv_field_count(const char *line) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.