file-handling · intermediate · ~15 min

Extract the Nth CSV field

Quote-aware CSV field splitting.

Challenge

Your job

int csv_field(const char *line, int idx, char *out, size_t cap);

Return the 0-based field idx from a CSV line in out (NUL-terminated). A field may be double-quoted, in which case commas inside the quotes are part of the field and the surrounding quotes are stripped. Return the field length, or -1 on NULL, out-of-range idx, or overflow.

Examples

  • "a,b,c", idx 1 → "b"
  • "x,\"hello, world\",z", idx 1 → "hello, world"

Hints

  1. Walk the line tracking an in_quotes flag.
  2. A comma only ends a field when NOT inside quotes.
  3. Copy the target field's bytes (minus the quotes) into out.

Why this matters

Real CSV has quoted fields containing commas — a naive split breaks on them. Getting this right is the heart of CSV handling.

Starter code

#include <stddef.h>
int csv_field(const char *line, int idx, char *out, size_t cap) {
    /* TODO */
    (void)line; (void)idx; (void)out; (void)cap;
    return -1;
}

Common mistakes

Splitting on every comma (breaks quoted fields). Not stripping the surrounding quotes. No overflow guard.

Edge cases to handle

Quoted field with an internal comma. First/last field. idx beyond the row.

Complexity

O(line length).

Background lessons

Up next

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