summaryrefslogtreecommitdiff
path: root/algorithms/string_reverse.cc
blob: 8b3e12c889ef4fa38af30eaf9594ed93fed33620 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>

using namespace std;


string rev(string &s)
{
  string res;
  for (int i = s.size()-1; i >= 0; i--) { // unsigned not!
    res += s[i];
  }
  return res;
}

void rev_inplace(string &s)
{
  char temp;
  int j = s.size()-1;
  for (int i = 0; i < j; i++, j--) {
    temp = s[i];
    s[i] = s[j];
    s[j] = temp;
  }
}


int main()
{
  string s = "Asdf";
  cout << rev(s) << endl << "---" << endl;
  cout << s << endl;
  rev_inplace(s);
  cout << s << endl;
  return 0;
}