Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Easiest Way to Reverse a String
Next article icon

Different Methods to Reverse a String in C++

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Reversing the string means the last character will be the first character, second last character will be second character and so on. In C++, we can reverse a string in various different ways as show below:

Table of Content

  • Using reverse() Function
  • Using Reverse Iterators
  • Using a Stack
  • Using Two Pointer Technique
  • Using Recursion

Using reverse() Function

C++ STL provides a built-in function reverse(), which can be used to reverse the string efficiently.

Example

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string s = "Hello World";      // Using reverse() function to reverse s     reverse(s.begin(), s.end());      cout << s;     return 0; } 

Output
dlroW olleH

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

Using Reverse Iterators

In C++, reverse iterators such as string.rbegin() and string.rend() are used to allow the traversal of string in reverse. We can use them to construct temporary reversed version of the string and then assign it to the original string.

Example

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string s = "Hello World";      // Creating a temporary reversed string   	// and assigning it to the s     s = string(s.rbegin(), s.rend());        	cout << s;     return 0; } 

Output
dlroW olleH

Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(n), for temporary reversed string.

Using a Stack

A stack can also be used to reverse a string due to its LIFO (Last In First Out) property. We can push all characters of the string into a stack and clear the current string. Then we pop characters from the stack and append them to the string one by one, resulting in the reversed string.

Example

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string s = "Hello World";     stack<char> st;      // Push each character of string into stack     for (char c : s)         st.push(c);      // Clear the string     s.clear();      // Pop characters from stack and add them to     // reversed string     while (!st.empty()) {         s.push_back(st.top());         st.pop();     }      cout << s;     return 0; } 

Output
dlroW olleH

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

Using Two Pointer Technique

In two-pointer technique, we use two pointers: one starting at the beginning (left) and one at the end (right) of the string. We move them towards the centre of the string and keep swapping the characters they point till they meet each other.

Example

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string s = "Hello World";      // Initialize two pointers: left at start     //  and right at the end of the string     int l = 0;     int r = s.length() - 1;      // Loop until the two pointers meet in the middle     while (l < r) {                // Swap characters at position left and right         swap(s[l], s[r]);          // Move the left pointer to right         l++;          // Move the right pointer to left         r--;     }      cout << s;     return 0; } 

Output
dlroW olleH

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

Note: Two pointer technique is implemented in the std::reverse() function.

Using Recursion

The two-pointer technique can also be implemented using recursion though it can be less space efficient and harder to understand.

Example

C++
#include <bits/stdc++.h> using namespace std;  // Function to reverse the string using recursion void revStr(string &s, int l, int r) {        // Base case: When left and right pointer meet     if (l >= r)         return;      // Swap characters at left and right     swap(s[l], s[r]);      // Recursive call to reverse remaining substring     revStr(s, l + 1, r - 1); }  int main() {     string s = "Hello World";      // Call the recursive function to reverse string     revStr(s, 0, s.length() - 1);      cout << s;     return 0; } 

Output
dlroW olleH

Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(n), for recursive stack.



Next Article
Easiest Way to Reverse a String

P

Priyam kakati, Ranju Kumari, Somesh Awasthi
Improve
Article Tags :
  • C++
  • C++ Basic Programs
  • cpp-string
  • STL
Practice Tags :
  • CPP
  • STL

Similar Reads

  • Easiest Way to Reverse a String
    Have you wondered which is the easiest way to reverse a string, Imagine you are giving a contest and an algorithm you have made requires reversing a string, you must be aware of the easiest way to reverse a string. What is a reversal of string:Reversing a string is the technique that reverses or cha
    4 min read
  • How to traverse a STL map in reverse direction?
    Map stores the elements in sorted order of keys. Now if we want to traverse it in reverse order we will use reverse_iterator of map. Syntax: map::reverse_iterator iterator_name; Reverse Iterator of map moves in backward direction on increment. So, we will point the reverse_iterator to the last eleme
    8 min read
  • C++ STL - Vector in Reverse Order
    Prerequisite: Vectors in C++ A vector can be printed in reverse order with the following methods: By traversing in the backward direction using indexingBy traversing in the backward direction using begin() and end() functions in C++ STLBy traversing in the backward direction using rbegin() and rend(
    3 min read
  • Iterate over characters of a string in C++
    Given a string str of length N, the task is to traverse the string and print all the characters of the given string. Examples: Input: str = "GeeksforGeeks" Output: G e e k s f o r G e e k s Input: str = "Coder" Output: C o d e r Naive Approach: The simplest approach to solve this problem is to itera
    3 min read
  • list reverse function in C++ STL
    The list::reverse() is a built-in function in C++ STL which is used to reverse a list container. It reverses the order of elements in the list container. Syntax: list_name.reverse()Parameters: This function does not accept any parameters. Return Value: This function does not return any value. It jus
    1 min read
  • Reverse given range of String for M queries
    Given a string S of length N and an array of queries A[] of size M, the task is to find the final string after performing M operations on the string. In each operation reverse a segment of the string S from position (A[i] to N-A[i]+1). Examples: Input: N = 6, S = "abcdef", M = 3, A = {1, 2, 3}Output
    15 min read
  • Different ways to access characters in a given String in C++
    String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose: operator[]at()subst
    4 min read
  • forward_list::reverse() in C++ STL
    std::forward_list::reverse() is an inbuilt function in CPP STL which reverses the order of the elements present in the forward_list. Syntax: forwardlist_name.reverse()Parameter: The function does not accept any parameter. Return value: The function has no return value. It reverses the forward list.
    1 min read
  • std::string::find_first_not_of in C++
    It searches the string for the first character that does not match any of the characters specified in its arguments. Here we will describe all syntaxes it holds. Return value : Index of first unmatched character when successful or string::npos if no such character found. Syntax 1: Search for the fir
    6 min read
  • std::string::insert() in C++
    In C++, the string::insert() function is used insert the characters or a string at the given position of the string. It is the member function of std::string class. The string::insert method can be used in the following ways to: Table of Content Insert a Single CharacterInsert a Single Character Mul
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences