If you're talking about reversing a sequence of words (no punctuation to worry about) then the standard way is to do it (in-place) is:
- reverse the entire string
- reverse the letters of each individual word
#include <iostream>
#include <string>
#include <algorithm>
// reverse the order of a string of words (does not deal with
// punctuation is a meaningful way but does handle spaces.)
void reverse_words(std::string& sentence) {
staticconstchar whitespace[] = " \t";
std::string::iterator i_beg = sentence.begin();
std::string::iterator i_end = sentence.end();
// reverse the whole string
std::reverse(i_beg, i_end);
// find the start of the first word
std::string::size_type from = sentence.find_first_not_of(whitespace);
std::string::size_type to = sentence.npos;
do {
// find the end of the next word
to = sentence.find_first_of(whitespace, from);
// and reverse it, handling the fact that it might be the last word
// with no trailing spaces or have trailing space
if(to != sentence.npos) {
std::reverse(i_beg + from, i_beg + to);
// look for the start of the next word
from = sentence.find_first_not_of(whitespace, to);
} else {
// run out of string
std::reverse(i_beg + from, i_end);
from = sentence.npos;
}
}
while(from != sentence.npos);
}
// test function
void test_reverse_words(const std::string& sentence) {
std::cout << "sentence:\n";
std::cout << "\"" << sentence << "\"\n";
std::string reversed_sentence = sentence;
reverse_words(reversed_sentence);
std::cout << "reversed sentence:\n";
std::cout << "\"" << reversed_sentence << "\"\n";
std::cout << "\n";
}
int main() {
// try a few different strings
test_reverse_words("an example sentence");
test_reverse_words(" another example sentence ");
test_reverse_words("one");
test_reverse_words(" ");
test_reverse_words("");
return 0;
}
C++ Shell output:
sentence:
"an example sentence"
reversed sentence:
"sentence example an"
sentence:
" another example sentence "
reversed sentence:
" sentence example another "
sentence:
"one"
reversed sentence:
"one"
sentence:
" "
reversed sentence:
" "
sentence:
""
reversed sentence:
""