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_fieldsfields; 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.038Empty 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
- Implement strlen · Count the characters before the terminating NUL.
- Implement strcmp · Compare two strings byte by byte.
- Bounded string copy · Copy a string into a fixed buffer, truncating safely.
- Reverse a string in place · Reverse the characters of a NUL-terminated string.
- Strip the line ending · Remove trailing CR and LF characters from a received line.
- Parse a hex byte · Convert two hexadecimal characters to a value.
- Format a hex byte · Write a byte as two upper-case hex characters without printf.
- Parse an unsigned number · Convert a decimal string to uint16_t, rejecting anything invalid.
- Integer to string · Format a signed 32-bit integer as decimal text without printf.
- Rotate an array · Rotate a buffer left by k positions in place.
- Search a calibration table · Find the table entry at or below a reading.
- Fix: long device names corrupt the status page · A name that fills its buffer has no terminator.
- Fix: reset leaves old data in the buffer · Clearing a buffer passed as a pointer clears only as many bytes as a pointer holds.
- Fix: copying a block corrupts the next variable · A copy loop runs one element past the end of both arrays.
- Drone GPS: check an NMEA sentence · Verify a GPS sentence's checksum before the navigation code trusts its position.