How to Reverse a String in C++

Jinku Hu Mar 12, 2025 C++ C++ String
  1. Method 1: Using the Standard Library
  2. Method 2: Using a Loop
  3. Method 3: Using Recursion
  4. Method 4: Use std::reverse() Algorithm
  5. Use std::copy() Algorithm to Reverse String
  6. Conclusion
  7. FAQ
How to Reverse a String in C++

Reversing a string is a fundamental task in programming that can be approached in various ways. In C++, this task can be accomplished using different methods, each with its own advantages. Whether you’re a beginner looking to grasp the basics or an experienced developer wanting to refresh your skills, understanding how to reverse a string in C++ can improve your coding proficiency.

In this article, we will explore several methods to reverse strings, complete with code examples and detailed explanations. By the end, you’ll have a solid grasp of how to implement string reversal in your C++ projects.

Method 1: Using the Standard Library

The simplest and most efficient way to reverse a string in C++ is by utilizing the Standard Library. The std::reverse function from the <algorithm> header is a powerful tool that allows you to reverse a string with minimal code. Here’s how you can do it:

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

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

Output:

!dlroW ,olleH

In this example, we first include the necessary headers: <iostream> for input and output, <algorithm> for the std::reverse function, and <string> for string manipulation. We create a string variable str initialized with “Hello, World!”. The std::reverse function takes two iterators as parameters: str.begin() and str.end(), which represent the start and end of the string, respectively. This function reverses the string in place, meaning that the original string is modified. Finally, we print the reversed string to the console.

This method is not only concise but also efficient, as it’s implemented in the C++ Standard Library, which is optimized for performance. If you’re looking for a quick and effective way to reverse strings, this is the method to use.

Method 2: Using a Loop

Another straightforward approach to reverse a string in C++ is by using a loop. This method gives you more control over the process and can be a great learning experience. Here’s how you can implement string reversal using a loop:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    std::string reversedStr;

    for (int i = str.length() - 1; i >= 0; i--) {
        reversedStr += str[i];
    }

    std::cout << reversedStr << std::endl;
    return 0;
}

Output:

!dlroW ,olleH

In this code snippet, we declare a string variable reversedStr to hold the reversed string. We then use a for loop that starts from the last character of the original string and iterates backward to the first character. Inside the loop, we append each character to reversedStr. Finally, we print the reversed string.

This method gives you a clear understanding of how strings can be manipulated character by character. However, it’s worth noting that while this approach is educational, it may not be the most efficient for larger strings compared to using the Standard Library.

Method 3: Using Recursion

If you’re interested in a more advanced technique, consider using recursion to reverse a string. This method might seem complex at first, but it’s an elegant solution once you grasp the concept. Here’s how you can reverse a string using recursion:

#include <iostream>
#include <string>

std::string reverseString(const std::string &str) {
    if (str.empty()) {
        return str;
    }
    return str.back() + reverseString(str.substr(0, str.length() - 1));
}

int main() {
    std::string str = "Hello, World!";
    std::string reversedStr = reverseString(str);
    std::cout << reversedStr << std::endl;
    return 0;
}

Output:

!dlroW ,olleH

In this example, we define a recursive function reverseString that takes a string as an argument. The base case for the recursion checks if the string is empty; if so, it returns the string. Otherwise, it concatenates the last character of the string (str.back()) with the result of calling reverseString on the remainder of the string (str.substr(0, str.length() - 1)). This process continues until the entire string is reversed.

This method showcases the power of recursion, but it’s essential to be cautious with performance, especially for long strings, as it may lead to stack overflow in extreme cases. Nevertheless, it’s a fantastic way to deepen your understanding of function calls and string manipulation.

Method 4: Use std::reverse() Algorithm

The std::reverse method is from the <algorithm> STL library, and it reverses the order of the elements in the range. The method operates on objects passed as arguments and does not return a new copy of the data, so we need to declare another variable to preserve the original string.

Note that the reverse function throws std::bad_alloc exception if the algorithm fails to allocate memory.

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

using std::cin;
using std::cout;
using std::endl;
using std::reverse;
using std::string;

int main() {
  string tmp_s = "This string will be reversed";
  cout << tmp_s << endl;

  string tmp_s_reversed(tmp_s);
  reverse(tmp_s_reversed.begin(), tmp_s_reversed.end());
  cout << tmp_s_reversed << endl;

  return EXIT_SUCCESS;
}

This code demonstrates the use of std::reverse from the C++ Standard Template Library to reverse a string. It creates a copy of the original string tmp_s and then uses reverse to modify this copy in-place. The reverse function operates on the range defined by the beginning and end iterators of the string.

This method is efficient and straightforward, directly modifying the string without needing additional memory allocation. It’s worth noting that while reverse is generally safe, it can throw a std::bad_alloc exception if memory allocation fails, though this is rare for string operations. This approach provides a clean and efficient way to reverse strings in C++, leveraging the power of STL algorithms.

Use std::copy() Algorithm to Reverse String

std::copy is another powerful algorithm, which can be utilized for multiple scenarios. This solution initializes a new string variable and modifies its size using the built-in resize method. Next, we call the copy method to fill the declared string with the original string’s data. Note, though, the first two parameters should be reverse iterators of the source range.

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

using std::cin;
using std::cout;
using std::endl;
using std::reverse;
using std::string;

int main() {
  string tmp_s = "This string will be reversed";
  cout << tmp_s << endl;

  string tmp_s_reversed;
  tmp_s_reversed.resize(tmp_s.size());
  copy(tmp_s.rbegin(), tmp_s.rend(), tmp_s_reversed.begin());
  cout << tmp_s_reversed << endl;

  return EXIT_SUCCESS;
}

The above code demonstrates another method to reverse a string using the std::copy algorithm. It creates a new string tmp_s_reversed and resizes it to match the original string’s length. Then, it uses copy with reverse iterators (rbegin() and rend()) of the original string to fill the new string with characters in reverse order. This approach efficiently creates a reversed copy of the string without modifying the original. It showcases the flexibility of STL algorithms and iterators in string manipulation, providing a clean and efficient solution for string reversal in C++.

In case the reversed string data need not be stored, we can use the copy() algorithm to directly output the string data in reverse order to the console as shown in the following code sample:

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

using std::cin;
using std::cout;
using std::endl;
using std::reverse;
using std::string;

int main() {
  string tmp_s = "This string will be reversed";
  cout << tmp_s << endl;

  copy(tmp_s.rbegin(), tmp_s.rend(), std::ostream_iterator<char>(cout, ""));

  return EXIT_SUCCESS;
}

This code demonstrates a concise method to reverse and print a string using the std::copy algorithm and stream iterators. It first outputs the original string, then uses copy with reverse iterators (rbegin() and rend()) of the string to directly output the characters in reverse order to the console. The std::ostream_iterator is used as the destination, which writes each character to cout. This approach efficiently reverses and prints the string without creating a new string object, making it memory-efficient for cases where only output is needed. It showcases the power of combining STL algorithms with stream iterators for simple and effective string manipulation in C++.

Conclusion

Reversing a string in C++ can be accomplished through various methods, each offering unique insights into string manipulation and programming concepts. From using the Standard Library for efficiency to exploring loops and recursion for deeper understanding, these techniques are invaluable tools in your coding arsenal. As you become more familiar with these methods, you’ll find that reversing strings is just the tip of the iceberg when it comes to string manipulation in C++. Keep practicing, and soon, you’ll be able to tackle even more complex string operations with confidence.

FAQ

  1. What is the easiest way to reverse a string in C++?
    The easiest way is to use the std::reverse function from the <algorithm> header.

  2. Can I reverse a string without using any libraries?
    Yes, you can manually reverse a string using loops or recursion.

  3. Is recursion a good method for reversing strings?
    While it’s elegant, recursion can be less efficient for long strings due to potential stack overflow issues.

  4. How do I reverse a string in place?
    You can reverse a string in place using the std::reverse function, which modifies the original string.

  5. What are the performance implications of different string reversal methods?
    Using the Standard Library is generally the most efficient, while manual methods like loops and recursion can be slower for large strings.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C++ String