Programmers learn & share
26 views

How reversing the string works in C++? Assume we have a string as “exam” the reverse form of this string will be “maxe”. There are some methods to reverse a string in c++ and we will be learning them in this article. 

 

Methods

 

  1. By creating a function

  2. Using the inbuilt function

  3. Printing reverse

 

For understanding all of the methods, let's take an example of a string. Assume we have a string

string str = “abcd”;

 

  • Creating a function

We can create our own function to reverse the string in c++. This method is pretty simple, in this method we are creating a function which will swap the characters of the string.

#include <iostream>
#include <bits/stdc++.h> 
using namespace std; 
  
void reverseStr(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 = "abcd"; 
    reverseStr(str); 
    cout << str; 
    return 0; 
}
  • Inbuilt function

C++ provides inbuilt function reverse() for reversing the characters. The function did all the work by itself, we only need to define it.

#include <iostream>
#include <bits/stdc++.h> 
using namespace std; 
 

int main() 
{ 
    string str = "abcd"; 
    reverse(str.begin(), str.end()); 
    cout << str; 
    return 0; 
}
  • Printing reverse

This method is a little similar to the first one. The only difference is in the first method we are swapping the characters of the string but in this method, we are going to print the characters of the string in the reverse order.

#include <iostream>
#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() 
{ 
    string s = "abcd"; 
    reverse(s);  
    return 0; 
}

Output

The output of all three programs will be the same. it will be “dcba”

Header files

I used the visual code for testing the programs and it just needed two header files.

#include<iostream> and #include<bits/stdc++.h>

If you are still getting error after adding these header files then try adding #include<algorithm.h>

 

If you have any doubt ask freely.

posted May 19 in c++ by (100 points)   | 26 views
2,220 questions
2,691 answers
59 comments
241 users