Drill

ProblemsC# › text

Wrap text to a label width

hardtextStringsGreedyParsingC#

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>

C# 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

public List<string> WordWrap(string text, int width) {
    
}

Worked examples

CallResult
WordWrap("the quick brown fox", 10)new List<string> { "the quick", "brown fox" }
WordWrap("a bb ccc", 3)new List<string> { "a", "bb", "ccc" }
WordWrap("supercalifragilistic is long", 5)new List<string> { "supercalifragilistic", "is", "long" }
WordWrap("one two", 20)new List<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 C#
public List<string> WordWrap(string text, int width) {
    var lines = new List<string>();
    if (width <= 0) return lines;
    string line = "";
    foreach (var w in text.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries)) {
        if (line.Length == 0) line = w;
        else if (line.Length + 1 + w.Length <= width) line += " " + w;
        else { lines.Add(line); line = w; }
    }
    if (line.Length > 0) lines.Add(line);
    return lines;
}

The same problem in another language

More text problems in C#