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.
Code
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
Text Wrap FormatterSoft-wrap paragraphs to a chosen column width for emails, commit messages, and terminal output, optionally breaking words longer than the width.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- How do you run Word Wrap Paragraphs At Width?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.