Wrap text to a label width
A shipping label printer takes a fixed number of characters per line, and a description has to be broken across lines without splitting words.
- Fill each line greedily: keep adding words while they still fit.
- Words are separated by whitespace and joined back with a single space.
- A word longer than the whole width goes on a line of its own, unbroken.
- A width of zero or less, or text with no words, gives an empty list.
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.
Where you start
public List<string> WordWrap(string text, int width) {
}
Worked examples
| Call | Result |
|---|---|
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;
}