Link to home
Start Free TrialLog in
Avatar of chenwei
chenwei

asked on

How to reverse a string

I have the following codes:

...
...
string line("this is a test");
...
...

how can I reverse this string line?

P.S.:
No c-function such as strrev().
Avatar of Hoegje
Hoegje

Homework maybe ?

How do you do something like that ? Think a bit for yourself. Take small steps at a time.. There are several ways to do this, so pick any of them..
You might consider reverse iterators (rbegin() and rend()). Enough said, assuming this is HW.
This sounds like homework so I will provide psuedo code to do it an easy fashion:

get initial string length
create a string of the same length
run a loop that counts down from length to zero
inside the loop place the original string[x] (assuming x is the decrementing variable) inside of newstring[length-x]

once the loop completes, you will have your string in reverse.  You may need to make it length-x-1 or add one and other such minute changes to make sure you dont exceed the allotted space and it gets put in the proper place.

hope that helps,
-kohashi
There's also a reverse function in STL.  This will work on string iterators.
You don't really need the new string.
You can simply swap the first and last, then the next pair and so on.
here is the code;

string line("this is a test");

//get the length of the string
int length = line.length();

//just print out backwards with a for loop
int i;
for(i=length-1;i>=0;i--){
    cout<<line[i];
}

cout<<endl;

good luck!
-zania22

zania22, you just did what Hoegje, rstaveley, kohashi, mnashadka, skp23 and many other EE members, who refrained from commenting, carefully avoided doing. Woops.
May be chenwei can use other methods doing it... like recursive
ASKER CERTIFIED SOLUTION
Avatar of xssass
xssass

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chenwei

ASKER

Thanks for the info from all sites. But truely to say, the method you gave me is not bad but is a very normal one which can be found out everywhere.

Originally what I want is to look for a simple function such as strrev() in C.

Here's the reverse iterators:
--------8<--------
#include <iostream>
#include <string>

int main()
{
      std::string test("this is a test");
      std::string reversed_test(test.rbegin(),test.rend());
      std::cout << reversed_test << '\n';
}
--------8<--------
I don't expect that it will score you points in a homework assignment, though. They's be more likely to be looking for loops etc.
reverse is found in <algorithm>
> They's

They'd

[Nearly mis-typed that the same way in my correction too. Must push my keyboard to the left a bit.]