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

std::vector<std::string> wordWrap(std::string text, int width) {
    
}

Worked examples

CallResult
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;
}

The same problem in another language

More text problems in C++