How to format an array of strings in lines with maxWidth without breaking the words in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char** formatLines(char** words, int wordCount, int maxWidth, int* lineCount) {
    char** result = NULL;
    *lineCount = 0;

    char currentLine[1024];  // buffer for building a line
    currentLine[0] = '\0';
    int currentLength = 0;

    for (int i = 0; i < wordCount; i++) {
        char* word = words[i];
        int wordLen = strlen(word);

        // If adding this word exceeds maxWidth, push current line
        if (currentLength + (currentLength == 0 ? 0 : 1) + wordLen > maxWidth) {
            // Save currentLine into result
            result = realloc(result, (*lineCount + 1) * sizeof(char*));
            result[*lineCount] = strdup(currentLine);
            (*lineCount)++;

            // Start new line
            strcpy(currentLine, word);
            currentLength = wordLen;
        } else {
            if (currentLength > 0) {
                strcat(currentLine, " ");
                currentLength++;
            }
            strcat(currentLine, word);
            currentLength += wordLen;
        }
    }

    // Push the last line if not empty
    if (currentLength > 0) {
        result = realloc(result, (*lineCount + 1) * sizeof(char*));
        result[*lineCount] = strdup(currentLine);
        (*lineCount)++;
    }

    return result;
}

int main() {
    char* words[] = {"This", "is", "a", "programming", "example", "of", "text", "wrapping"};
    int wordCount = sizeof(words) / sizeof(words[0]);
    int maxWidth = 12;

    int lineCount;
    char** lines = formatLines(words, wordCount, maxWidth, &lineCount);

    for (int i = 0; i < lineCount; i++) {
        printf("\"%s\"\n", lines[i]);
        free(lines[i]);  // free each line
    }
    free(lines);  // free array of pointers

    return 0;
}



/*
run:

"This is a"
"programming"
"example of"
"text"
"wrapping"

*/

 



answered Dec 2, 2025 by avibootz

Related questions

...