Word Wrap Paragraphs At Width

Greedy wrapping breaks text into lines no wider than the limit, splitting only at spaces and pushing an overlong word to its own line.

GoCli Tooling

Code

snippet
package main

import (
	"fmt"
	"strings"
)

// wrapAt 把一段文本 (paragraphs) 按最大宽度折行:只在空格处断开,长单词不拆
func wrapAt(text string, width int) []string {
	var lines []string
	var line strings.Builder
	for _, word := range strings.Fields(text) {
		switch {
		case line.Len() == 0:
			line.WriteString(word)
		case line.Len()+1+len(word) <= width:
			line.WriteByte(' ')
			line.WriteString(word)
		default:
			lines = append(lines, line.String())
			line.Reset()
			line.WriteString(word)
		}
	}
	if line.Len() > 0 {
		lines = append(lines, line.String())
	}
	return lines
}

func main() {
	text := "the quick brown fox jumps over a lazy dog near the riverbank every morning"
	for i, line := range wrapAt(text, 24) {
		fmt.Printf("%2d | %-24s| %d\n", i+1, line, len(line))
	}
}

What the code does

The compressed view: all the work sits in the functions wrapAt and main, doing all the work.

A single loop drives the file — for _, word := range strings.Fields(text).

What to watch for

  • The runtime alone is required here — no packages, no install step.

Applying it

The main signature is written as func wrapAt(text string, width int) []string

The entry point wires wrapAt together — run it once and the whole demo flows.

Statements that carry the weight

for i, line := range wrapAt(text, 24) {
	fmt.Printf("%2d | %-24s| %d\n", i+1, line, len(line))
}
lines = append(lines, line.String())

Interactive Tools for This Topic

FAQ

How do you run Word Wrap Paragraphs At Width?
Execute it straight away — the program needs nothing beyond the runtime.