inverting a string

G

Gary Wessle

hi

I tried to do this, something is not correct.

#include <iostream>
#include <string>
using namespace std;


string inverse(string s)
{

// string inv = "";
// int i = s.size(); // reinterpret_cast no go
// while(i>0){
// inv += s.substr(i,1);
// i--;
// }

string inv = "";
string::iterator begin = s.begin();
string::iterator end = s.end();
(while begin != end){
inv += *begin;
}



}



int main(){

string k = "IRS";
cout << inverse(k) << endl;

}
 
G

Gary Wessle

Gary Wessle said:
hi

I tried to do this, something is not correct.

#include <iostream>
#include <string>
using namespace std;


string inverse(string s)
{

// string inv = "";
// int i = s.size(); // reinterpret_cast no go
// while(i>0){
// inv += s.substr(i,1);
// i--;
// }

string inv = "";
string::iterator begin = s.begin();
string::iterator end = s.end();
(while begin != end){
inv += *begin;
}



}



int main(){

string k = "IRS";
cout << inverse(k) << endl;

}

#include <algorithm>
string str = "sunny";
reverse(str.begin(), str.end())
cout << str << endl;
 
J

Jerry Coffin

[email protected] says... said:
string inverse(string s)

The library already provides enough to let you do this in one line of
code quite easily. First of all, when you want to traverse some
collection (and for this purpose, a string qualifies as a collection) in
reverse, you usually want to use a reverse_iterator. Most collections
provide begin() and end(). Those that support reverse_iterators normally
suppose rbegin() and rend() as well.

std::string also has a ctor that takes a pair of iterators as arguments
to specify the contents of the new string.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top