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

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

/*
    This program wraps a string into lines of maximum width w.

    Method:
    - Split the input text into words using strings.Fields().
    - Build each line until adding another word would exceed the width.
    - When the limit is reached, store the line and begin a new one.
    - Uses slices and string operations for clear and efficient processing.
*/

func wrapText(text string, w int) string {
    words := strings.Fields(text) // Split on whitespace
    line := ""
    var result []string

    for _, word := range words {

        // If line is empty, start it with the word
        if len(line) == 0 {
            line = word
        } else {
            // Check if adding the next word exceeds width
            if len(line)+1+len(word) <= w {
                line += " " + word
            } else {
                // Store the completed line
                result = append(result, line)
                line = word
            }
        }
    }

    // Add the final line
    if len(line) > 0 {
        result = append(result, line)
    }

    return strings.Join(result, "\n")
}

func main() {
    sample :=
        "Go provides useful built-in tools for handling strings. " +
        "This program demonstrates how to wrap text cleanly and efficiently."

    wrapped := wrapText(sample, 35)
    fmt.Println(wrapped)
}


/*
run:

Go provides useful built-in tools
for handling strings. This program
demonstrates how to wrap text
cleanly and efficiently.

*/

 



answered Jul 11 by avibootz
...