tags:

views:

184

answers:

5

in the code below i m trying to reverse the string there is no compile time error but ,nothing is displayed .what is wrong ?

   string string1="arunachalam";

   void reverseStr()
   {        
       for(int i=string1.length();i<0;i--)
       {
          cout<<string1[i];
       }
   }
+4  A: 

Problem is in the int i=string1.length() statement, since indexes are 0 based it should be int i=string1.length() - 1 Also, your i < 0 condition is wrong, i'll leave it to work it out yourself.

Naveen
And the "i<0" should be "i<=0".
imaginaryboy
no it should be i>=0..
Naveen
i also tried that
Arunachalam
+8  A: 

Your loop condition i < 0 is the main culprit. The loops immediately exits because the length of a string is never negative. Replace with i >= 0.

You should also have i = string1.length() - 1 as string indexes are zero-based. Thus:

for(int i = string1.length() - 1; i >= 0; i--) {
    cout << string1[i];
}
Jason
All this confusion shows that a clean idiom is needed for backwards looping. And it exists (besides reverse iterators): `for (unsigned i = string1.size(); i --> 0; )` http://stackoverflow.com/questions/1642028/what-is-the-name-of-this-operator :)
UncleBens
+1  A: 

I'm sorry, but it should be i>0 to make this work

allan
Not if you want to display the first character of the string.
UncleBens
+1  A: 

Hi,

By far the cleanest, off-by-one-safe and stop-condition-safe solution for this is using the reverse iterator - assuming it was a std::string you are using.

string string1="arunachalam";
void reverseStr()
{
   string::const_reverse_iterator  cur;
   // .rbegin() returns iterator to reverse-begin, i.e. the end ...
   // operator++ on a reverse iterator does move it in the "right"
   // (desired) direction.
   for(cur=string1.rbegin(); cur!=string1.rend(); cur++)
       cout << *cur;
}
haavee
+2  A: 

A function is more useful if it does not rely on global variables. Using arguments and return values such as with the signature:

const string& reverseStr(const string& s);

would be more useful. The definition could use the reverse_iterator from std::string thus:

const string& reverseStr(const string& s)
{
    return string(s.rbegin(), s.rend());
}

followed by actual use:

string string1="arunachalam";

cout << reverseStr(string1); // XXX: add an endl, if needed
vapace