Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Five Ways to Reverse a String of Words (ANSI C++ version)

by eyepopslikeamosquito (Archbishop)
on Dec 15, 2006 at 08:46 UTC ( [id://589994]=note: print w/replies, xml ) Need Help??


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; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://589994]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-04-23 20:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found