So I'm trying to come up with a good C++ solution to the prompt
"Reverse words in a string (words are separated by one or more spaces). Now do it in-place. By far the most popular string question!"
and what I have now is a monstrosity:
void reverse_words ( std::string & S )
{
/*
Programming interview question: "Reverse words in a string (words are separated by one or more spaces). Now do it in-place. By far the most popular string question!"
http://maxnoy.com/interviews.html
*/
if (S.empty()) return;
std::string::iterator ita = S.begin() , itb = S.end() - 1;
while (ita != itb)
{
if (*ita != ' ')
{
std::string sa; // string to hold the current leftmost sequence of non-whitespace characters
std::string::iterator tempa = ita; // iterator to the beginning of sa within S
while (ita != ' ' && ita != itb) sa.push_back(*ita++); // fill sa
while (*itb == ' ' && itb != ita) --itb; // move itb back to the first non-whitespace character preceding it
std::string sb; // string to hold the current rightmost sequence of non-whitespace characters
std::string::iterator tempb = itb; // iterator to the end of sb within S
while (*itb != ' ' && itb != ita) sb.push_back(*itb--); // fill sb
S.replace(tempa, ita-tempa, sb); // replace the current leftmost string with the current rightmost one
S.replace(tempb, itb-tempb, sa); // and vice-versa
}
else
{
++ita;
}
}
}
I think I have the right idea (find the first string, swap it with the last, find the next string after the first, swap it with the one before the last, etc.), but I need some better tools to make this happen. How can I exploit the standard library to solve this problem?