Drill

ProblemsC++ › text

Title-case a heading

mediumtextStringsParsingC++

The CMS title-cases headings on save, but the house style leaves the small joining words in lowercase unless one of them opens the heading.

titleCase(heading: string) → 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 titleCase(std::string heading) {
    
}

Worked examples

CallResult
titleCase(std::string("the lord of the rings"))std::string("The Lord of the Rings")
titleCase(std::string("a tale OF two cities"))std::string("A Tale of Two Cities")
titleCase(std::string("hello"))std::string("Hello")
titleCase(std::string("of mice and men"))std::string("Of Mice and Men")

Hint

Handle index 0 as its own case, then let the small-word list decide for the rest.

Reference solution in C++
std::string titleCase(std::string heading) {
    std::set<string> small{"a", "an", "and", "as", "at", "but", "by", "for", "in", "of", "on", "or", "the", "to"};
    if (heading.empty()) return "";
    std::vector<string> parts;
    string cur;
    for (char c : heading) {
        if (c == ' ') { parts.push_back(cur); cur.clear(); }
        else cur += static_cast<char>(tolower(static_cast<unsigned char>(c)));
    }
    parts.push_back(cur);
    string result;
    for (size_t i = 0; i < parts.size(); i++) {
        if (i) result += ' ';
        string w = parts[i];
        if (i > 0 && small.count(w)) result += w;
        else if (w.empty()) result += w;
        else { w[0] = static_cast<char>(toupper(static_cast<unsigned char>(w[0]))); result += w; }
    }
    return result;
}

The same problem in another language

More text problems in C++