Summarise With AI
ChatGPT
Perplexity
Claude
Gemini
Grok
ChatGPT
Perplexity
Claude
Gemini
Grok
Back

Reverse a String in C++ | Simple & Efficient Methods

29 Nov 2025
5 min read

Key Takeaways From the Blog

  • Reversing a string in C++ can be done using loops, recursion, stacks, two-pointer techniques, and STL functions.
  • std::reverse() is the simplest and most efficient built-in method.
  • Custom functions using loops or recursion help understand fundamental programming concepts.
  • Two-pointer approach is memory-efficient and fast for in-place reversal.
  • Special cases include reversing C-style strings and reversing individual words while keeping order.
  • Common pitfalls involve off-by-one errors, null terminators, and improper handling of character arrays.

Introduction

Reversing​‍​‌‍​‍‌​‍​‌‍​‍‌ a string in C++ is one of the basic programming tasks that can be found in various areas such as data processing, algorithm design, etc. In short, if you are using strings in competitive programming, doing some text transformations, or coming up with data encryption solutions, then learning the different ways of string reversal will be of great help. C++ offers several approaches to reverse a string, each with other efficiency and implementation complexity.

This article will examine different methods for reversing a string in C++. First, we will take a look at simple methods using loops and recursion, and then we will move on to more advanced techniques such as the Standard Template Library (STL) and two-pointer methods. So, after reading this article, you will know different methods of string reversal in C++ and be able to decide which one to ​‍​‌‍​‍‌​‍​‌‍​‍‌use.

What Do You Mean by Reverse a String?

Reversing a string in C++ means rearranging its characters in the opposite order. For example, if the input string is "hello", the reversed output will be "olleh". This can be useful in various applications, such as palindrome checking, string manipulation, and coding challenges. C++ provides multiple ways to reverse a string, such as the built-in reverse() function from the <algorithm> library, manual character swapping, or a stack.

Methods To Reverse a String in C++

In C++, reversing a string can be accomplished using various methods, each suitable for different scenarios. Here are some common approaches:

1. std::reverse() Function to Reverse a String in C++

The Standard Library provides the std::reverse() function to reverse a string in C++ in the <algorithm> header, which can reverse the order of elements in a range. This function can be applied directly to a string to reverse its characters and used to reverse a string in C++ built-in function.

Program to Reverse a String in C++ Using std::reverse() Function

#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    std::reverse(str.begin(), str.end());
    std::cout << str; // Output: !dlroW ,olleH
    return 0;
}

Output

!dlroW ,olleH

Explanation

  • #include <algorithm>: Includes the STL algorithm library where std::reverse is defined.
  • str.begin() and str.end(): Iterators pointing to the first and one-past-last characters of the string.
  • std::reverse(str.begin(), str.end()): Reverses all characters in the string in place.
  • std::cout << str;: Prints the reversed string.
  • Advantage: Very concise and efficient (O(n) time, O(1) extra space).

Bottom Line: std::reverse() is the fastest and simplest method, perfect for everyday string reversal tasks.

2. Using a Custom Function to Reverse a String in C++

You can write a custom function to reverse a string by swapping characters from the beginning with those from the end until you reach the middle.

Program to Reverse a String in C++ Using a Custom Function

#include <iostream>
#include <string>

void reverseString(std::string &str) {
    int n = str.length();
    for (int i = 0; i < n / 2; ++i) {
        std::swap(str[i], str[n - i - 1]);
    }
}

int main() {
    std::string str = "Hello, World!";
    reverseString(str);
    std::cout << str; // Output: !dlroW ,olleH
    return 0;
}

Output

!dlroW ,olleH
  • ter from the end.
  • By stopping at the middle, each character is swapped exactly once.
  • Advantage: In-place, no extra memory, helps understand indexing and loops.

Quick Recap: Manual loops build strong programming intuition and prepare learners for problem-solving beyond library functions.

3. Reversing Each Word in a String Without Changing the Word Order

If you want to reverse the characters of each word in a sentence while maintaining the original word order, you can do so by iterating through the string and reversing each word individually.

Code to Reverse Each Word in a String in C++

#include <algorithm>
#include <iostream>
#include <string>

void reverseWords(std::string &str) {
    int start = 0;
    int end = 0;
    int n = str.length();

    while (end <= n) {
        if (end == n || str[end] == ' ') {
            std::reverse(str.begin() + start, str.begin() + end);
            start = end + 1;
        }
        ++end;
    }
}

int main() {
    std::string str = "Hello World";
    reverseWords(str);
    std::cout << str; // Output: olleH dlroW
    return 0;
}

Output

olleH dlroW

Explanation

  • start and end: Track the beginning and end of each word.
  • while (end <= n): Iterates over the string including the last character.
  • if (end == n || str[end] == ' '): Detects the end of a word (space or end of string).
  • std::reverse(str.begin() + start, str.begin() + end): Reverses characters of the word in place.
  • start = end + 1: Move start to the next word.
  • Advantage: Useful for reversing words individually while keeping their positions intact.

Quick Note: Reversing words rather than the full string is vital for applications like coding challenges and sentence-based transformations.

4. Using a Stack to Reverse a String in C++

A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. This means that the last element pushed onto the stack is the first one to be removed. This characteristic makes a stack an excellent choice for reversing a string since we can store characters in the stack and retrieve them in reverse order.

Program to Reverse a String in C++ using Stack

#include <iostream>
#include <stack>
#include <string>

std::string reverseUsingStack(const std::string &str) {
    std::stack<char> s;
    for (char ch : str) {
        s.push(ch);  // Push each character onto the stack
    }
    
    std::string reversed;
    while (!s.empty()) {
        reversed += s.top(); // Get the top character (last pushed character)
        s.pop(); // Remove the top character from the stack
    }
    return reversed;
}

int main() {
    std::string str = "Hello, World!";
    std::cout << reverseUsingStack(str); // Output: !dlroW ,olleH
    return 0;
}

Output

!dlroW ,olleH

Explanation

  • std::stack<char> s: Creates a stack of characters.
  • for (char ch : str) s.push(ch): Pushes each character onto the stack.
  • s.top(): Retrieves the last pushed character.
  • s.pop(): Removes the top character from the stack.
  • reversed += s.top(): Builds the reversed string one character at a time.
  • Advantage: Intuitive for beginners, preserves original string if needed, uses O(n) extra space.

Time Complexity Analysis

  • Pushing each character onto the stack: O(n)
  • Popping each character from the stack: O(n)
  • Appending to the string: O(n) (In modern implementations, string operations can be amortized to O(1) per character)
  • Total Complexity: O(n)

Why Use a Stack?

The Last-In-First-Out (LIFO) nature of stacks makes them an excellent choice for reversing sequences. Since the last element added to the stack is the first one removed, pushing characters onto the stack and then popping them results in a reversed order. This simple mechanism provides an efficient way to reverse strings without manually swapping characters.

Another advantage of using a stack is its intuitive and easy-to-implement approach. Unlike other methods that require complex pointer manipulation or additional loops, the stack method simply involves pushing and popping elements. This makes it a beginner-friendly and structured way to reverse data while maintaining clarity in the code.

Bottom Line: Stacks provide a clear, structured way to reverse strings, especially when teaching data structures.

5. Using Recursion to Reverse a String in C++

Recursion is a technique where a function calls itself to break down a problem into smaller subproblems until a base case is reached. It is used to reverse a string without using a library function. When applied to string reversal, recursion allows us to progressively shorten the string and build the reversed version by appending characters in reverse order.

Code to Reverse a String using Recursion

#include <iostream>
#include <string>

std::string reverseRecursively(const std::string &str) {
    if (str.empty()) { // Base case: If the string is empty, return an empty string
        return "";
    }
    return reverseRecursively(str.substr(1)) + str[0]; // Recursive call with substring
}

int main() {
    std::string str = "Hello, World!";
    std::cout << reverseRecursively(str); // Output: !dlroW ,olleH
    return 0;
}

Output

!dlroW ,olleH

Explanation

  • if (str.empty()) return "";: Base case; empty string returns itself.
  • str.substr(1): Creates a substring excluding the first character.
  • reverseRecursively(str.substr(1)) + str[0]: Recursively reverses the remaining string and appends the first character at the end.

Downsides of Using Recursion

One major downside of using recursion to reverse a string is higher memory usage. Each recursive call consumes stack space, as function calls are stored in the call stack until the base case is reached. For long strings, this can lead to excessive memory consumption, potentially causing a stack overflow error if the recursion depth exceeds the system's limit. Unlike iterative methods that operate within a fixed memory space, recursion continuously adds new function calls, making it less memory-efficient.

Another significant concern is performance inefficiency due to the repeated creation of substrings. The function str.substr(1) generates a new substring in every recursive call, resulting in an O(n²) time complexity. This means that for a string of length n, the function performs n recursive calls, and each call involves an O(n) substring operation. 

Optimized Recursive Approach (Using Pointers)

A more efficient recursive solution avoids substring creation by using two pointers.

#include <iostream>
#include <string>

void reverseHelper(std::string &str, int left, int right) {
    if (left >= right) {
        return; // Base case: Pointers have crossed
    }
    std::swap(str[left], str[right]); // Swap characters
    reverseHelper(str, left + 1, right - 1); // Recursive call
}

void reverseRecursivelyOptimized(std::string &str) {
    reverseHelper(str, 0, str.length() - 1);
}

int main() {
    std::string str = "Hello, World!";
    reverseRecursivelyOptimized(str);
    std::cout << str; // Output: !dlroW ,olleH
    return 0;
}

Output

!dlroW ,olleH

Explanation

  • left and right: Track characters from start and end.
  • if (left >= right) return;: Base case, stops recursion when pointers meet.
  • std::swap(str[left], str[right]): Swap characters in place.
  • reverseHelper(str, left + 1, right - 1): Move pointers towards the center.
  • Advantage: Reduces memory overhead, O(n) time, O(n) stack space.

Quick Recap: Recursion is a great learning tool, but for production, iterative or STL-based methods are preferable.

6. Using Two Pointers to Reverse a String in C++

Using​‍​‌‍​‍‌​‍​‌‍​‍‌ the two-pointer approach to reverse a string is probably the coolest and the most efficient way to do it without a library function. Basically, the two pointers point to the first and last characters of the string, respectively; these characters are swapped, and both pointers are moved toward the centre of the string, and the process is repeated until the entire string is reversed. Unlike the recursive or stack-based versions, this method changes the string directly, so it takes less memory and is ​‍​‌‍​‍‌​‍​‌‍​‍‌quicker.

Code to Reverse a String Using Two Pointers

#include <iostream>
#include <string>

void reverseWithTwoPointers(std::string &str) {
    int left = 0, right = str.length() - 1; // Initialize two pointers
    while (left < right) { // Loop until pointers meet in the middle
        std::swap(str[left], str[right]); // Swap characters
        left++;  // Move left pointer forward
        right--; // Move right pointer backward
    }
}

int main() {
    std::string str = "Hello, World!";
    reverseWithTwoPointers(str);
    std::cout << str; // Output: !dlroW ,olleH
    return 0;
}

Output

!dlroW ,olleH

Explanation

  • left starts at the beginning, right at the end.
  • while (left < right): Loops until pointers meet.
  • std::swap(str[left], str[right]): Swaps characters from both ends.
  • left++, right--: Move pointers inward.
  • Advantage: Fast, memory-efficient, O(n) time, O(1) space.

Quick Note: Two-pointer technique is ideal for competitive programming and memory-sensitive applications.

Comparison with Other Methods

There are multiple ways to reverse a string in C++, each with its own trade-offs in terms of time complexity, space usage, and code readability. Here’s a quick comparison of some common techniques:

Method Time Complexity Space Complexity Notes
Two-Pointer Approach O(n) O(1) Most efficient method, performs in-place reversal without extra memory.
Naive Recursion O(n²) O(n) Slow due to repeated creation of substrings; mainly for learning purposes.
Optimized Recursion (with Pointers) O(n) O(n) Faster than naive recursion; still uses call stack space.
Using Stack O(n) O(n) Simple to implement, but uses extra memory for the stack.
Using Temporary String O(n) O(n) Creates a reversed copy; easy to implement but not space-efficient.
Using STL reverse() Function O(n) O(1) Most convenient and reliable for production; performs in-place reversal.

Quick Note: Two-pointer technique is ideal for competitive programming and memory-sensitive applications.

Reversing C-Style Strings (Character Arrays) in C++

C-style strings are arrays of characters terminated by a null character ('\0'). Reversing them requires careful handling to maintain the null terminator and avoid buffer overflows.

1. Using strrev() Function (Non-Standard)

The strrev() function can reverse a C-style string in place. However, note that strrev() is not part of the C++ standard library and may not be available on all platforms.

#include <iostream>
#include <cstring>  // For strrev()
using namespace std;

int main() {
    char str[] = "hello"; 
    strrev(str);  // Reverses the string in place
    cout << str;  // Output: olleh
    return 0;
}

2. Manual In-Place Reversal Using Swap

You can reverse a character array manually by swapping characters from both ends, similar to the two-pointer approach for std::string:

#include <iostream>
#include <cstring>  // For strlen()
using namespace std;

int main() {
    char str[] = "hello"; 
    int n = strlen(str);  // Get the length of the string

    // Loop to swap characters from both ends
    for (int i = 0; i < n / 2; i++) {
        swap(str[i], str[n - i - 1]);  // Swap characters at positions i and (n - i - 1)
    }

    cout << str;  // Output: olleh
    return 0;
}

3. Creating a New Reversed Character Array

Alternatively, you can create a new character array and copy characters from the original in reverse order:

#include <iostream>
#include <cstring>  // For strlen()
using namespace std;

int main() {
    char str[] = "hello"; 
    int n = strlen(str);  // Get the length of the string
    char rev[100];        // New array to store reversed string

    // Copy characters from the original string in reverse order
    for (int i = 0; i < n; i++) {
        rev[i] = str[n - i - 1];  // Assign characters in reverse order
    }

    rev[n] = '\0';  // Add null terminator to the reversed string

    cout << rev;  // Output: olleh
    return 0;
}

Key Points to Remember

  • Always ensure null terminator (\0) is preserved.
  • Manual swaps are safest across platforms.
  • Edge cases include empty strings and special characters.

Common Errors and Debugging Tips When Reversing Strings in C++

Reversing strings in C++ is usually simple. However, some mistakes that are common can lead to bugs or unexpected behavior. Below are the issues that happen most often and the ways to debug them using C++ key terms and functions:

1. Off-by-One Errors

The biggest trap of off-by-one errors is miscalculating loop boundaries. This is especially true when for-loops or while-loops are used to swap characters. An example of such a case is swapping up to n/2 which is a proper operation, but if <= is used instead of < then the middle character will be swapped twice without the programmer realizing it or it will be missed entirely.

Debugging Tip:

Check again the conditions of your loops and the calculations of your indices. The swapping of a string of length n should be done when i < n/2.

2. Issues with Null Terminators in Character Arrays

C-style strings (character arrays) have to be terminated with a null terminator ('\0'). When a programmer reverses or copies a string manually and does not set the null terminator, string functions may go beyond the intended end causing garbage output or crashes.

Debugging Tip:

Make sure that the character array you have reversed always ends with '\0'. Setting rev[n] = '\0'; is done after copying when a new reversed array is being ​‍​‌‍​‍‌​‍​‌‍​‍‌created.

3. Misuse of Standard Library Functions and Iterators

When using functions like std::reverse, it's crucial to pass the correct iterators. Passing begin() and end() works for std::string, but not for character arrays. Also, forgetting to include the correct headers (like <algorithm>) can cause compile-time errors.

Debugging Tip:
Use str.begin() and str.end() for std::string. For character arrays, use manual loops or functions like strrev. Always include necessary headers.

4. Partial Strings from Input (cin vs getline)

Using cin to read input will stop at the first whitespace, resulting in partial strings. This can cause only part of the intended string to be reversed.

Debugging Tip:
Use getline(std::cin, str) to read full lines, especially when input may contain spaces.

5. Modifying Constant Strings

Trying to reverse a string declared as const or a string literal will result in errors or undefined behavior, as these cannot be modified.

Debugging Tip:
Work with modifiable strings (e.g., std::string or non-const character arrays) when reversing in place.

6. Unexpected Behavior with Unicode or Special Characters

Invisible Unicode characters or multi-byte characters may not reverse as expected with standard functions, leading to display or logic issues.

Debugging Tip:
For Unicode strings, use std::wstring and Unicode-aware functions. Be mindful that reversing by bytes may break multi-byte characters.

7. Incorrect Use of swap

When manually reversing, use std::swap() for clarity and safety instead of temporary variables. This reduces the chance of assignment mistakes.

8. Debugging Suggestions

  • Test with edge cases: empty strings, single characters, strings with spaces or special characters.
  • Print intermediate results to verify each step.
  • Use a debugger to step through loop indices and check variable values.
  • If reversing character arrays, check for null terminators before and after reversal.

Conclusion

There​‍​‌‍​‍‌​‍​‌‍​‍‌ are many ways to write a program that reverses a string in C++, in fact, you can do that by a simple loop, recursion, or even by using built-in functions from the Standard Template Library. Every technique you use has certain benefits and drawbacks in terms of how fast the program runs, how easy it is to understand the code, and how much memory it consumes. Although std::reverse() is the quickest and most handy way, it is still very important to know how to do it manually with loops and recursion in order to understand the core concepts of programming.

With vertex values of different approaches one can gain deeper knowledge about string manipulations and also their performance considerations. By learning the different ways of reversing strings in C++, your programming skills will become more solid, be it for coding interviews, making text-processing applications, or just enhancing your problem-solving ​‍​‌‍​‍‌​‍​‌‍​‍‌abilities.

Why It Matters?

Mastering different methods of string reversal helps build a solid foundation in algorithm design, memory management, and efficient coding practices. These techniques are frequently used in coding challenges, competitive programming, and real-world applications, making them crucial for improving problem-solving abilities and preparing for technical interviews.

Practical Advice for Learners

  • Understand the theory behind methods (recursion, stack, two-pointer) to choose the best approach.
  • Test solutions with edge cases like empty strings or special characters.
  • Start with built-in functions like std::reverse() for simplicity, then explore manual methods.
  • Avoid recursion for large inputs to reduce memory usage; use iterative methods instead.
  • Use memory-efficient techniques like the two-pointer approach for large datasets.
  • Don't neglect C-style strings, as they're common in many challenges and low-level programming.

Frequently Asked Questions (FAQs)

1. How can I reverse a string in C++ without using any built-in functions?

You can reverse a string manually using a for loop or a while loop by swapping characters from the beginning and end of the string until you reach the middle.

2. What is the most efficient way to reverse a string in C++?

The most efficient way is to use the std::reverse() function from the <algorithm> header, which is optimized for performance and works in O(n) time complexity.

3. Can I reverse a string in C++ using recursion?

Yes, you can use recursion to reverse a string by swapping the first and last characters and recursively calling the function for the remaining substring.

4. How does the two-pointer technique help in reversing a string?

The two-pointer technique involves using two indices, one starting at the beginning and the other at the end of the string, and swapping characters until they meet in the middle.

5. Is it possible to reverse a string without modifying the original string?

Yes, you can create a new string and store the reversed characters in it, preserving the original string unchanged.

6. How do I reverse only words in a sentence but keep the word order intact?

You can split the sentence into words using a delimiter (such as spaces), reverse each word individually, and then reconstruct the sentence.

7.​‍​‌‍​‍‌​‍​‌‍​‍‌ Can I use a stack in C++ to reverse a string?

Indeed, every character of the string may be pushed onto a stack and then popped off one at a time to get the reversed string.

8. What are the common mistakes that should not be made in reversing a string?

Some of the common mistakes in which one might fall are: forgetting to properly handle null-terminated strings, not recognizing spaces or special characters, and going beyond array bounds when dealing with C-style ​‍​‌‍​‍‌​‍​‌‍​‍‌strings.

9. What is string reversal in C++?

String reversal is the process of reversing the order of characters in a string. For example:

Input: "hello" Output: "olleh"

10. How can I reverse a string in-place?

You can reverse a string in-place using a two-pointer approach:

#include <iostream> 
#include <string> 
using namespace std;

int main() { 
    string str = "hello";    // Initialize the string "hello"
    int n = str.length();    // Get the length of the string
    
    for (int i = 0; i < n / 2; i++) {  // Loop through the first half of the string
        swap(str[i], str[n - i - 1]);  // Swap characters at the beginning and end
    } 
    
    cout << str;  // Output the reversed string
    // Output: olleh
}

Notes:

  • Works with character arrays as well.
  • Efficient because it doesn’t use extra memory.

11. How do I reverse a C-style string (character array)?

#include <iostream>
#include <cstring>  // For strlen()
using namespace std;

int main() {
    char str[] = "hello";  // Initialize a C-style string (character array)
    int n = strlen(str);   // Get the length of the string using strlen()

    for (int i = 0; i < n / 2; i++) {  // Loop through the first half of the string
        swap(str[i], str[n - i - 1]);  // Swap characters at the beginning and end
    }

    cout << str;  // Output the reversed string
    // Output: olleh
}

12. How does special characters affect reversal?

Special characters (spaces, punctuation) are treated like any other character.

Example:

#include <iostream>
#include <algorithm>  // For std::reverse
#include <string>     // For std::string
using namespace std;

int main() {
    string s = "hi! there";    // Create a string with words and punctuation
    reverse(s.begin(), s.end()); // Reverse the entire string in place
    
    cout << s;  // Output the reversed string
    // Output: "ereht !ih"
}

Read More Articles

Chat with us
Chat with us
Talk to career expert