DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to reverse a string in C++?

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.


title: "originally posted here 👇"

canonical_url: https://kodlogs.com/blog/455/how-to-reverse-a-string-in-c

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; 
}
Enter fullscreen mode Exit fullscreen mode

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; 
}
Enter fullscreen mode Exit fullscreen mode

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; 
}
Enter fullscreen mode Exit fullscreen mode

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 and #include

If you are still getting error after adding these header files then try adding #include

If you have any doubt ask freely.

Top comments (0)