reversing a string method

Hi people I've been studying all day trying to find a way to reverse a string and I've found one the question is pretty much why does this code actually work?

newString += one[i]; this line of code in particular one[i] would imply that String is an array so is this true,is a string actually an array?

and I'm also just wondering how this algorithm actually works if anyone could help break this down I'd be very greatfull thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
#include <string>

using namespace std;

int main()
{

    string one("hello");
    string newString = "";

    for(int i = one.size() -1; i >=0; i--){

        newString += one[i];
    }

    cout << newString;
}
newString += one[i]; this line of code in particular one[i] would imply that String is an array so is this true,is a string actually an array?

It implies no such thing. What it does imply is that it has an overload for operator[] which lets you access individual characters of the string. Under the hood, std::string is implemented as an array (assuming you're using a modern compiler - the requirement didn't exist until the C++11 standard and at least one library maker took advantage of that.) But you shouldn't think of it as an array. It is a string.


and I'm also just wondering how this algorithm actually works if anyone could help break this down I'd be very greatfull thanks

Given that one is equal to "hello" and result is an empty string, if we go from the last character of one to the first character of one and add each character from one to the end of result as we go, then result ends up being the reverse of one.

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream> 
#include <string>

using namespace std;

int main () 
{
  string input = "Hello world!";
  string output(input.rbegin(), input.rend());

  cout << "Input = " << input;
  cout << "\nOutput = " << output;
 
  return 0;
}
Topic archived. No new replies allowed.