Verbose Word/Phrase Reverse in C++ Same exact story as Verbose Word/Phrase Reverse in Node.js, but in C++.

If you don't want to follow the link:


  The assignment is to:
  
  
  If input is a word, reverse the word. (e.g. "hello" becomes "olleh")
  If input is a phrase, reverse the order of the phrase but not the actual words. (e.g. "united states of america" becomes "america of states united")
  
  
  The other restriction is I am only allowed to use the C++ equivalent of Java String's length, substring, charAt, concatenation and indexOf methods.


Code:

#include &lt;iostream&gt;

std::string ReverseWord(const std::string&amp; word) {
    std::string reverse;
    for (unsigned long i = word.length() - 1; i &lt;= word.length(); --i) reverse += word[i];
    return reverse;
}

std::string ReversePhrase(const std::string&amp; phrase) {
    unsigned long last_space = phrase.length();
    std::string out;
    for (unsigned long i = phrase.length() - 1; i &lt;= phrase.length(); --i) {
        if (phrase[i] == ' ') {
            out += phrase.substr(i + 1, last_space - i - 1) + " ";
            last_space = i;
        }
    }

    out += phrase.substr(0, last_space);
    return out;
}

int pa12() {
    std::string in;
    std::cout &lt;&lt; "Enter a word or phrase: ";
    getline(std::cin, in);

    if (std::find(in.begin(), in.end(), ' ') == in.end()) {
        std::cout &lt;&lt; "The reversed word is: " &lt;&lt; ReverseWord(in) &lt;&lt; std::endl;
    } else {
        std::cout &lt;&lt; "The reversed phrase is: " &lt;&lt; ReversePhrase(in) &lt;&lt; std::endl;
    }

    return 0;
}
Prefer to use iterators to iterate through data structures

Look how nice your ReverseWord function becomes when you use the provided rbegin() and rend():

std::string ReverseWord(const std::string&amp; word) {
  return std::string(word.rbegin(), word.rend());
}


Use algorithms when possible

Similarly, your finding of the spaces can be done with a simple string::find() instead.

Apart from that, the code looks reasonable. However...

High level

This is an algorithm that's traditionally implemented as an in-place transformation on a string_view (or array of chars, pre-c++17)

You definitely would want to revisit this and tackle the problem from that angle instead. 

It's a bit of a "trick" question, as there is a very simple algorithm to do it, but it's not exactly obvious at first glance. That's why the question asks to reverse a word first. Once you figured out how to reverse a word in-place, the solution to "reverse the words of a phrase" becomes a bit more clear.