Open In App

How to Reverse a String in C++?

Last Updated : 19 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Reversing a string means replacing the first character with the last character, second character with the second last character and so on. In this article, we will learn how to reverse a string in C++.

Examples

Input: str = "Hello World"
Output: dlroW olleH
Explanation: The last character is replaced by first character, second last character by second character and so on.

Input: str = "Geeks for Geeks"
Output: skeeG rof skeeG
Explanation: The last character is replaced by first character, second last character by second character and so on.

Reverse a String in C++

C++ STL provides the std::reverse() method that reverses the order of elements in the given range. We can use this function to reverse the string by passing the iterators to the beginning and the end of the string. This method is defined inside <algorithm> header file.

Syntax

std::reverse(str.begin(), str.end());

where str is the string to be reversed.

Code Implementation

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

int main() {
    string str = "Hello World";

    // Reverse the string using the std::reverse() 
    reverse(str.begin(), str.end());

    cout << str;
    return 0;
}

Output
dlroW olleH

Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(1)

There are a few more methods to reverse the string in C++. Please refer this article - Different Methods to Reverse a String.


Next Article
Practice Tags :

Similar Reads