Drill

ProblemsC++ › text

Cut a description to length

mediumtextStringsParsingC++

A listing card has room for a fixed number of characters, and a description cut mid-word looks broken.

truncateWords(text: string, limit: int) → 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::string truncateWords(std::string text, int limit) {
    
}

Worked examples

CallResult
truncateWords(std::string("The quick brown fox"), 10)std::string("The quick...")
truncateWords(std::string("Supercalifragilistic"), 5)std::string("Super...")
truncateWords(std::string("Short"), 10)std::string("Short")
truncateWords(std::string("a b c d e f"), 5)std::string("a b c...")

Hint

Look at the character sitting at `limit`: if it is a space, the slice is already clean and needs no trimming back.

Reference solution in C++
std::string truncateWords(std::string text, int limit) {
    if (limit <= 0) return "";
    if ((int) text.size() <= limit) return text;
    string cut = text.substr(0, limit);
    if (text[limit] != ' ') {
        size_t sp = cut.rfind(' ');
        if (sp != string::npos && sp > 0) cut = cut.substr(0, sp);
    }
    while (!cut.empty() && isspace(static_cast<unsigned char>(cut.back()))) cut.pop_back();
    return cut + "...";
}

The same problem in another language

More text problems in C++