reverse string function explanation help!

Hi Guys

Can you help me understand the below function. I know it reverses a string namely "s" and assigns it to string variable answer then returns the original string "s" in reverse order as variable string "answer"... but how is it being reversed? My brain just cannot comprehend this and i want to understand, knowing it works this way isn't good enough. please help.

1
2
3
4
5
6
7
8
9
10
  string reverse(string s)
{
    string answer = "";

    for(int i = 0 ; i < s.size(); i++)
        {
            answer = s[i] + answer;
        }
    return answer;
}
but how is it being reversed?

Very inefficiently.

1
2
3
4
5
6
7
8
9
10
  string reverse(string s)
{
    string answer = "";

    for(int i = 0 ; i < s.size(); i++)
        {
            answer = s[i] + answer;
        }
    return answer;
}


Consider what happens when reverse is fed a particular string, say "cab"

s.size() yields 3, so the for loop iterates 3 times.

The first time through the loop, answer is an empty string. So we take s[0] and prepend it to that empty string ( in effect 'c' + "".) At the conclusion of the first iteration of the loop, answer is "c".

The second time through the loop answer is "c". So we take s[1] and prepend it to that string (in effect 'a' + "c") which means at the conclusion of the second iteration of the loop answer is "ac".

The third time through the loop answer is "ac". So we take s[2] and prepend it to that string (in effect 'b' + "ac") which means at the conclusion of the third iteration of the loop answer is "bac".

And that is what we return.
Finally! Thank you very much. it all seems so simple now.
Topic archived. No new replies allowed.