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

1 Answer

0 votes
package main

import (
    "fmt"
)

func formatLines(words []string, maxWidth int) []string {
    var result []string
    currentLine := ""
    currentLength := 0

    for _, word := range words {
        wordLen := len(word)

        // If adding this word exceeds maxWidth, push current line
        if currentLength+(func() int {
            if currentLine == "" {
                return 0
            }
            return 1
        }())+wordLen > maxWidth {
            if currentLine != "" {
                result = append(result, currentLine)
            }
            currentLine = word
            currentLength = wordLen
        } else {
            if currentLine != "" {
                currentLine += " "
                currentLength++
            }
            currentLine += word
            currentLength += wordLen
        }
    }

    // Push the last line if not empty
    if currentLine != "" {
        result = append(result, currentLine)
    }

    return result
}

func main() {
    words := []string{"This", "is", "a", "programming", "example", "of", "text", "wrapping"}
    maxWidth := 12

    lines := formatLines(words, maxWidth)

    for _, line := range lines {
        fmt.Printf("\"%s\"\n", line)
    }
}



/*
run:

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

*/

 



answered Dec 2, 2025 by avibootz

Related questions

...