Skip to content

Instantly share code, notes, and snippets.

@alexandream
Last active January 11, 2017 11:19
Show Gist options
  • Save alexandream/d5060c03a354e798b6851a8d1249ac73 to your computer and use it in GitHub Desktop.
Save alexandream/d5060c03a354e798b6851a8d1249ac73 to your computer and use it in GitHub Desktop.
A simple function to word wrap a C string to a specific maximum line length
/* As an example, when using a line width of 25, the string:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
Becomes:
"Lorem ipsum dolor sit
amet, consectetur
adipiscing elit, sed do
eiusmod tempor incididunt
ut labore et dolore magna
aliqua."
The String:
"From R7RS:
Programming languages should be designed not by piling feature on top of feature,
but by removing the weaknesses and restrictions that make additional features appear necessary."
Becomes (notice how line breaks in original are kept intact):
"From R7RS:
Programming languages
should be designed not by
piling feature on top of
feature,
but by removing the
weaknesses and
restrictions that make
additional features
appear necessary."
*/
char*
word_wrap_inplace(char* input, int line_length) {
char* result = input;
int base = 0;
int last_space = 0;
int i = 0;
if (result == NULL) {
return NULL;
}
while (result[base+i] != '\0') {
if (i > line_length && base < last_space) {
/* We're bigger than maximum and we know of a place to break. */
result[last_space] = '\n';
base = last_space = last_space +1;
i = 0;
}
else if (result[base+i] == '\n') {
/* Good. The string broke before the maximum. Just reset scan. */
base = last_space = base+i +1;
i = 0;
}
else {
if (result[base+i] == ' ') {
last_space = base+i;
}
i++;
}
}
return result;
}
char*
word_wrap(char* input, int line_length) {
int result_len = strlen(input) + 1;
char* result = malloc(result_len * sizeof(char));
if (result == NULL) {
return NULL;
}
memcpy(result, input, result_len * sizeof(char));
return word_wrap_inplace(result, line_length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment