Different methods to reverse a string in C/C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to understand different methods to reverse a string in C/C++.

Example

User-defined reverse() function −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//function to reverse given string
void reverse_str(string& str){
   int n = str.length();
   for (int i = 0; i < n / 2; i++)
      swap(str[i], str[n - i - 1]);
}
int main(){
   string str = "tutorialspoint";
   reverse_str(str);
   cout << str;
   return 0;
}

Using in-built reverse() function −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   string str = "tutorialspoint";
   reverse(str.begin(), str.end());
   cout << str;
   return 0;
}

Printing reverse of a given string−

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void reverse(string str){
   for (int i=str.length()-1; i>=0; i--)
      cout << str[i];
}
int main(void){
   string s = "tutorialspoint";
   reverse(s);
   return (0);
}

Output

tniopslairotut
raja
Published on 23-Mar-2020 08:20:55
Advertisements