0

Just learning c++. The following function is my attempt to reverse a string (doesn't work and I don't know why). Thank you for spotting my stupidity.

#include <iostream>
using namespace std;

string r(string s)
{
    int len = s.length();
    for (int i = 0; i < len; i++)
    {
        char temp = s[i];
        s[i] = s[len - i];
        s[len - i] = temp; 
    }

    return s;
}

int main()
{
    cout << r("ASTRING");
}

It changes first letter of the string to ' ' and outputs STRING

18
  • 9
    Work thru your reversal on paper, or in a debugger. Which elements get swapped on the first iteration of the loop? Which elements get swapped on the last? Commented Sep 29, 2020 at 22:42
  • 2
    hi, perhaps s[len - i] is out of bounds on the first iteration. Commented Sep 29, 2020 at 22:44
  • 1
    @Cool_Cornflakes std::reverse() already does that in a safe and robust way. Don't reinvent the wheel, especially not if it comes out as a square. Commented Sep 29, 2020 at 22:48
  • 4
    The problem is you go all the way through the string. You should stop at half way, otherwise you swap them all, then swap them all back whilst traversing the second half. Commented Sep 29, 2020 at 22:48
  • 1
    @Cool_Cornflakes To get familiar with c++, you should concentrate to learn about the facilities you can have from the standard library. That's more productive IMO. Also step through your code line by line with the debugger. You'll find the problem fairly fast. Commented Sep 29, 2020 at 22:50

2 Answers 2

1

Another simple way:

string r(string s)
{
    int len = s.length();
    string temp;
    for (int i = len - 1; i > -1; i--)
    {
        temp.push_back(s[i]);
    }
    s = temp;
    return s; // or return temp;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Firstly, string.length() returns length with '\0' which mean end of string, so you need to delete 1.
Secondly, you don't travel whole string, you should stop at the middle, i/2 will just do this whatever the length is.

finally :

string r(string s)
{
    int len = s.length() - 1;
    for (int i = 0; i < len/2; i++)
    {
        char temp = s[i];
        s[i] = s[len - i];
        s[len - i] = temp;
    }

    return s;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.