Reverse a String (Iterative) C++


There are many ways defined to reverse a string in the C++ code including stack, In-place, and iteration. In this sample, a simple string will be reversed iteratively with the following algorithm;

Algorithm

START
   Step-1: Input the string
   Step-2: Get the length of the string using length() method
   Step-3: Swap the last character to first using for loop
   Step-4: Print
END

Incompatibility of the above calculation, the accompanying code in c++ language tried as following;

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void strReverse(string& str){
   int n = str.length();
   // Swap character starting from two
   cout<<"interative reverse (Tomhanks)::";
   for (int i = 0; i < n / 2; i++)
      swap(str[i], str[n - i - 1]);
}
int main(){
   string str = "Tomhanks";
   strReverse(str);
   cout << str;
   return 0;
}

Output

As the above code compiled, the given string “Tomhanks” will be printed in reverse order as follows;

Iterative reverse (Tomhanks):: sknahmoT

Updated on: 23-Dec-2019

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements