string reverse

could someone explains what is line[line.size() - 1 - i] ? i'm kinda confuse with that.
also why line.size()/2 is divide by 2?

if i input : i love chicken!
output will be !nekcihc evol i


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 using namespace std;

//function.


int main()
{
  string line;
  char tmp;
  int i;
  cout << "Enter a string: " << endl;
  getline(cin, line);
  cout << "line is: " << line << endl;
  for( i = 0; i < line.size()/2; i++)
    {
      tmp = line[i];
      line[i] = line[line.size() - 1 - i];
      line[line.size() - 1 - i] = tmp;
    }
  cout << "The reverse is: " << line << endl;


  return 0;
}

Last edited on
The code is effectively swapping the characters on opposite sides of the string. The first and last are swapped, then second and second-to-last, then third and third-to-last, and so on until it gets to the middle of the string (and thats where the divide-by-two comes in).

Its looks a bit convoluted. A more readable version would be this:

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

int main()
{

    std::cout << "Enter a string: ";
    std::string line;
    std::getline(std::cin, line);

    int i = 0;   // set i to index 0
    int j = line.size()-1; // set j to final index of line

    while (i <= j) // until i and j have not crossed over
    {
        std::swap(line[i], line[j]); // swap elements at index i and j
        i++; // move i forward
        j--; // move j back
    }

    std::cout << "Line reversed is: " << line << "\n";
}
Last edited on
Is it good practice to rely on <iostream> for std::string and std::swap?
Why not use std::reverse()?
@zifi: Maybe not, but in a quick demo like this its no big deal.

@Sakurawhatever: When you were a beginner, did you go straight to STL functions? Or did you actually try learning the logic and code that these STL functions based on?Calling std::reverse() gives a beginner no information or understanding as to how the string is reversed.
Last edited on
@Arslanwhatever: Unless the teacher forbids him to use it, there is no reason why we should not use std::reverse(). It makes our code looks neater and more self-documenting.
@Sakurawhatever: You are missing the point. The OP is clearly trying the understand the code (which reverses a string). What good of an answer is "just use std::reverse() bro" ?

Or maybe I should have answered with "send me a private message", lol.
Last edited on
Topic archived. No new replies allowed.