http://qs321.pair.com?node_id=589994


in reply to Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell)

Here are two versions in plain ANSI C++.

#include <string> #include <sstream> #include <iostream> using namespace std; static string reverseWords(string const& instr) { istringstream iss(instr); string outstr; string word; iss >> outstr; while (iss >> word) outstr = word + ' ' + outstr; return outstr; } int main() { string s = " one two \t three four "; string sret = reverseWords(s); cout << "in='" << s << "' " << "out='" << sret << "'" << endl; return 0; }
and
#include <string> #include <sstream> #include <iostream> #include <deque> #include <algorithm> using namespace std; static string reverseWords(string const& instr) { istringstream iss(instr); deque<string> dqs; copy(istream_iterator<string>(iss), istream_iterator<string>(), front_inserter(dqs)); if (dqs.empty()) return ""; ostringstream oss; copy(dqs.begin(), --dqs.end(), ostream_iterator<string>(oss, " ")) +; oss << dqs.back(); return oss.str(); // ... or build string directly instead of using ostringstream // string outstr(dqs.front()); // for (deque<string>::const_iterator i = ++dqs.begin(); i != dqs. +end(); ++i) // outstr += ' ' + *i; // return outstr; } int main() { string s = " one two \t three four "; string sret = reverseWords(s); cout << "in='" << s << "' " << "out='" << sret << "'" << endl; return 0; }