Strings & text
13 steps in 5 sets of C.
C strings are a convention, not a type: a pointer and a promise that there is a zero byte somewhere ahead. Everything in this tour follows from that.
Copying and building, comparing and searching, splitting and parsing, and transforming. Thirteen steps, and roughly half of them are about not walking off the end of a buffer.
Copying & building
- Copying stringsstrcpy trusts you completely; strncpy does not always terminate. Know both traps.
- snprintf is the safe buildersnprintf bounds the write and tells you what the full length would have been.
- Concatenationstrcat appends at the existing terminator, so the target must have room for both.
- Building a string on the heapJoining an unknown number of pieces: measure, allocate once, then copy.
Comparing & searching
- Comparing stringsstrcmp orders text and never returns a bool, so compare its result against zero.
- Searching inside textstrchr finds a character, strstr a substring, and both return NULL when absent.
- Substring search by handThe naive scan, written out, because knowing the cost is the point.
Splitting & parsing
- Splitting with strtokstrtok cuts a string into tokens in place, which means it modifies the input.
- Parsing numbers properlystrtol reports where it stopped and sets errno on overflow — atoi does neither.
- Trimming whitespaceTrimming in place: walk forward for the start, backward for the end.
Transforming
- Case conversion and comparisonConverting in place, and comparing without regard to case.
- Wrapping text to a widthEmitting words until the column runs out, then starting a line.
Encore
- csv_parse.cA complete CSV reader: split lines into fields, trim them, report a summary.