user14229433
user14229433

Reputation:

c++ function to reverse string doesn't work

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

Upvotes: 0

Views: 290

Answers (2)

jery
jery

Reputation: 34

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

Upvotes: 0

Osman Durdag
Osman Durdag

Reputation: 965

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

Upvotes: 1

Related Questions