Wrapping text to a width in C
Emitting words until the column runs out, then starting a line.
#include <stdio.h>
#include <string.h>
void wrap(const char *words[], size_t n, size_t width) {
size_t column = 0;
for (size_t i = 0; i < n; i++) {
size_t len = strlen(words[i]);
if (column > 0 && column + 1 + len > width) {
printf("\n");
column = 0;
} else if (column > 0) {
printf(" ");
column++;
}
printf("%s", words[i]);
column += len;
}
printf("\n");
}
How it works
- The column counter decides when to break.
- A break resets the counter and emits a newline.
- The separator is only written between words, never before the first.
Keywords and builtins used here
charconstelseforifsize_tvoidwrap
The run, in numbers
- Lines
- 19
- Characters to type
- 358
- Tokens
- 128
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 77 seconds.
Step 2 of 2 in Transforming, step 12 of 13 in Strings & text.