Drill

ProblemsGo › text

Wrap text to a label width

hardtextStringsGreedyParsingGo

A shipping label printer takes a fixed number of characters per line, and a description has to be broken across lines without splitting words.

wordWrap(text: string, width: int) → list<string>

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func wordWrap(text string, width int) []string {
	
}

Worked examples

CallResult
wordWrap("the quick brown fox", 10)[]string{"the quick", "brown fox"}
wordWrap("a bb ccc", 3)[]string{"a", "bb", "ccc"}
wordWrap("supercalifragilistic is long", 5)[]string{"supercalifragilistic", "is", "long"}
wordWrap("one two", 20)[]string{"one two"}

Hint

Track the current line as a string. Before adding a word, check whether the line plus a space plus the word still fits.

Reference solution in Go
func wordWrap(text string, width int) []string {
	lines := []string{}
	if width <= 0 {
		return lines
	}
	line := ""
	for _, w := range strings.Fields(text) {
		switch {
		case line == "":
			line = w
		case len(line)+1+len(w) <= width:
			line += " " + w
		default:
			lines = append(lines, line)
			line = w
		}
	}
	if line != "" {
		lines = append(lines, line)
	}
	return lines
}

The same problem in another language

More text problems in Go