#include <stdio.h>
#include <string.h>
#include <ctype.h>
/*
wrap_text()
-----------
Wraps a given string into lines of maximum width `w`.
Method:
- Scan the input string word by word.
- Use a buffer to build the current line.
- If adding the next word would exceed width, print the line and start a new one.
- This uses standard library functions such as strlen(), memcpy(), and isspace()
to keep the implementation clear and efficient.
Notes:
- The function prints the wrapped text directly.
- It avoids unnecessary dynamic allocation by using fixed-size buffers.
*/
void wrap_text(const char *text, size_t w) {
char line[1024] = {0}; /* Buffer for the current line */
size_t line_len = 0;
const char *p = text;
while (*p) {
/* Skip leading spaces */
while (isspace((unsigned char)*p)) {
p++;
}
/* Extract next word */
char word[256];
size_t word_len = 0;
while (*p && !isspace((unsigned char)*p)) {
if (word_len < sizeof(word) - 1) {
word[word_len++] = *p;
}
p++;
}
word[word_len] = '\0';
if (word_len == 0) {
continue;
}
/* If line is empty, start it with the word */
if (line_len == 0) {
memcpy(line, word, word_len + 1);
line_len = word_len;
}
/* Otherwise check if adding the word exceeds width */
else if (line_len + 1 + word_len <= w) {
line[line_len] = ' ';
memcpy(line + line_len + 1, word, word_len + 1);
line_len += 1 + word_len;
}
/* If it exceeds width, print the current line and start a new one */
else {
printf("%s\n", line);
memcpy(line, word, word_len + 1);
line_len = word_len;
}
}
/* Print the last line if not empty */
if (line_len > 0) {
printf("%s\n", line);
}
}
int main() {
const char *sample =
"C provides useful standard library functions for handling strings. "
"This program demonstrates how to wrap text cleanly and efficiently.";
wrap_text(sample, 35);
return 0;
}
/*
run:
C provides useful standard library
functions for handling strings.
This program demonstrates how to
wrap text cleanly and efficiently.
*/