Drill

ProblemsC++ › warmup

Reverse the order of the words

easywarmupStringsParsingC++

A text filter turns a sentence back to front, word by word, without disturbing the words themselves.

reverseWords(text: 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 reverseWords(std::string text) {
    
}

Worked examples

CallResult
reverseWords(std::string("the quick brown fox"))std::string("fox brown quick the")
reverseWords(std::string(" a b "))std::string("b a")
reverseWords(std::string("one"))std::string("one")
reverseWords(std::string(""))std::string("")

Hint

Split on whitespace, reverse the list, join with a single space.

Reference solution in C++
std::string reverseWords(std::string text) {
    istringstream in(text);
    std::vector<string> words;
    string w;
    while (in >> w) words.push_back(w);
    string result;
    for (size_t i = words.size(); i > 0; i--) {
        if (!result.empty()) result += ' ';
        result += words[i - 1];
    }
    return result;
}

The same problem in another language

More warmup problems in C++