Drill

ProblemsJava › text

Wrap text to a label width

hardtextStringsGreedyParsingJava

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>

Java 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

List<String> wordWrap(String text, int width) {
    
}

Worked examples

CallResult
wordWrap("the quick brown fox", 10)Main.<String>ls("the quick", "brown fox")
wordWrap("a bb ccc", 3)Main.<String>ls("a", "bb", "ccc")
wordWrap("supercalifragilistic is long", 5)Main.<String>ls("supercalifragilistic", "is", "long")
wordWrap("one two", 20)Main.<String>ls("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 Java
List<String> wordWrap(String text, int width) {
    List<String> lines = new ArrayList<>();
    if (width <= 0) return lines;
    StringBuilder line = new StringBuilder();
    for (String w : text.trim().split("\\s+")) {
        if (w.isEmpty()) continue;
        if (line.length() == 0) line.append(w);
        else if (line.length() + 1 + w.length() <= width) line.append(' ').append(w);
        else { lines.add(line.toString()); line = new StringBuilder(w); }
    }
    if (line.length() > 0) lines.add(line.toString());
    return lines;
}

The same problem in another language

More text problems in Java