Reverse a String (Iterative) C++

C++Server Side ProgrammingProgramming

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
raja
Published on 23-Dec-2019 06:24:14
Advertisements