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
std::vector<std::string> wordWrap(std::string text, int width) {
}
Worked examples
| Call | Result |
|---|---|
wordWrap(std::string("the quick brown fox"), 10) | std::vector<std::string>{std::string("the quick"), std::string("brown fox")} |
wordWrap(std::string("a bb ccc"), 3) | std::vector<std::string>{std::string("a"), std::string("bb"), std::string("ccc")} |
wordWrap(std::string("supercalifragilistic is long"), 5) | std::vector<std::string>{std::string("supercalifragilistic"), std::string("is"), std::string("long")} |
wordWrap(std::string("one two"), 20) | std::vector<std::string>{std::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++
std::vector<std::string> wordWrap(std::string text, int width) {
std::vector<string> lines;
if (width <= 0) return lines;
istringstream in(text);
string w, line;
while (in >> w) {
if (line.empty()) line = w;
else if ((int) (line.size() + 1 + w.size()) <= width) line += " " + w;
else { lines.push_back(line); line = w; }
}
if (!line.empty()) lines.push_back(line);
return lines;
}