Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Different Methods to Reverse a String in C++
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
Different Methods to Reverse a String in C++

P

Priyam kakati, Ranju Kumari, Somesh Awasthi
Improve
Article Tags :
  • C++
  • STL
  • cpp-string
  • C++ Basic Programs
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
    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
    string::rbegin() and string::rend() in C++
    The std::string::rbegin() and std::string::rend() functions in C++ are used to fetch the reverse iterators to the string. They are the member function of std::string and are used when we want to iterate the string in reverse. In this article, we will learn how to use string::rbegin() and string::ren
    2 min read
    std::string::back() in C++ with Examples
    This function returns a direct reference to the last character of the string. This shall only be used on non-empty strings. This can be used to access the last character of the string as well as to append a character at the end of the string. Length of the string remains unchanged after appending a
    2 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