Simvik

Split a delimited line

Tokenise a line in place without allocating memory. A medium embedded C problem (Arrays and strings), run and graded in the browser.

medium · Arrays and strings · parsing · tokenizer · nmea

Split line at every delim character, in place: overwrite each delimiter with a NUL and store a pointer to the start of each field in fields.

  • A line with k delimiters has k + 1 fields. Empty fields are kept as empty strings.
  • Store at most max_fields fields; once that many are stored, stop and ignore the rest of the line.
  • Return the number of fields stored.

Starter code

size_t split_fields(char *line, char delim, char *fields[], size_t max_fields) {
  // "a,b" -> fields[0] = "a", fields[1] = "b", returns 2
  return 0;
}

Example tests

Three fields

char line[] = "GPGGA,123519,4807.038";
char *f[4];
size_t n = split_fields(line, ',', f, 4);
printf("%u %s %s %s\n", (unsigned)n, f[0], f[1], f[2]);

Expected output:

3 GPGGA 123519 4807.038

Empty field in the middle

char line[] = "a,,c";
char *f[4];
size_t n = split_fields(line, ',', f, 4);
printf("%u [%s] [%s] [%s]\n", (unsigned)n, f[0], f[1], f[2]);

Expected output:

3 [a] [] [c]

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems