Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,710 questions

55,474 answers

573 users

How to wrap a string into lines of width w in C

2 Answers

0 votes
#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.

*/

 



answered Jul 11 by avibootz
edited Jul 11 by avibootz
0 votes
#include <stdio.h>
#include <ctype.h>

void wrap_text(const char *s, int w) {
    int col = 0;

    while (*s) {
        /* Skip leading spaces */
        if (col == 0) {
            while (*s == ' ') s++;
        }

        /* If the next word won't fit, break the line */
        const char *word = s;
        int len = 0;
        while (word[len] && word[len] != ' ') len++;

        if (col > 0 && col + 1 + len > w) {
            putchar('\n');
            col = 0;
        }

        /* Print the word */
        if (col > 0) {
            putchar(' ');
            col++;
        }

        for (int i = 0; i < len; i++) {
            putchar(word[i]);
        }

        col += len;
        s += len;

        /* Skip spaces between words */
        while (*s == ' ') s++;
    }

    putchar('\n');
}


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.
 
*/

 



answered Jul 11 by avibootz
...