HOWTO · C++

How to Reverse a String in C++

This article introduces how to reverse a string in C++. Explore various methods including using the Standard Library, loops, and recursion. Each method is explained with clear code examples and detailed explanations to help you understand string manipulation in C++. Whether you're a beginner or an experienced coder, this guide is a valuable resource for enhancing your C++ skills.

On this page

To reverse a C++ string, choose whether the original should change. Construct a new std::string from reverse iterators when you need to keep the source, or call std::reverse on the string when changing it in place is appropriate. std::copy can fill a destination string or write reversed characters directly to a stream. A loop makes the element-by-element process clear; recursion is mainly useful as a learning exercise.

Choose a string-reversal approach

For most code, use reverse iterators to create a separate result, or std::reverse to reorder an existing string. Both operate on the elements of std::string, which are char values. If the text contains UTF-8, reversing those bytes can break multibyte characters; see the final section before using these techniques for human language text.

Reverse a string with reverse iterators

A string’s rbegin() and rend() iterators traverse its elements from the last to the first. Passing them to the std::string constructor creates a reversed copy and leaves the source unchanged. This is a direct option when both strings need to remain available.

Run this example:

#include <iostream>
#include <string>

int main() {
    const std::string original = "Hello, C++!";
    const std::string reversed(original.rbegin(), original.rend());
    std::cout << "Original: " << original << '\n';
    std::cout << "Reversed: " << reversed << '\n';
}

The constructor takes a pair of iterators that define the order of elements in the new string. The original remains available for later use, while the new string owns its reversed sequence.

Reverse a string in place with std::reverse

std::reverse is an algorithm declared in <algorithm>. It swaps elements in the half-open range from the first iterator up to, but not including, the second. It changes the supplied range and returns no reversed copy. The following program applies it to a copy so that it can print both versions:

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

int main() {
    const std::string original = "Hello, C++!";
    std::string changed = original;
    std::reverse(changed.begin(), changed.end());
    std::cout << "Original: " << original << '\n';
    std::cout << "Changed: " << changed << '\n';
}

If the original itself should change, call std::reverse(original.begin(), original.end()) on a non-const string instead. This operation does not need to allocate a second string. Do not rely on the algorithm to report allocation failure: it rearranges the elements in the range and has no allocation step of its own.

Create a reversed string with std::copy

std::copy copies elements from an input range to a destination range; it does not resize a destination string. Give the destination enough elements before copying. Reverse iterators make the copied order run backward. When you only need to display the characters, an output iterator avoids storing another string.

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

int main() {
    const std::string original = "Hello, C++!";
    std::string reversed(original.size(), '\0');
    std::copy(original.rbegin(), original.rend(), reversed.begin());

    std::cout << "Copy: " << reversed << '\n';
    std::cout << "Stream: ";
    std::copy(original.rbegin(), original.rend(),
              std::ostream_iterator<char>(std::cout));
    std::cout << '\n';
}

The string constructor creates a destination with the required number of elements, so the output range is large enough for the source. The std::ostream_iterator writes each copied character to std::cout; <iterator> declares it. Qualifying the algorithm names with std:: makes their namespace explicit.

Reverse a string with a loop

A loop can append elements from the end of the source toward its beginning. Iterating with std::string::size_type avoids converting the string length to a signed integer. The decrement-and-check form below also stops before subtracting from zero:

#include <iostream>
#include <string>

int main() {
    const std::string original = "Hello, C++!";
    std::string reversed;
    reversed.reserve(original.size());

    for (std::string::size_type i = original.size(); i > 0; --i) {
        reversed.push_back(original[i - 1]);
    }

    std::cout << reversed << '\n';
}

Reserving capacity is an optional optimization that can avoid repeated growth while appending. The loop is useful for understanding the operation or adding per-element logic; for ordinary reversal, the standard-library approaches are shorter and easier to recognize.

Reverse a string recursively

Recursion can express reversal by taking the last element and then processing the preceding substring. This version returns a new string and illustrates that definition:

#include <iostream>
#include <string>

std::string reverseString(const std::string& value) {
    if (value.size() < 2) {
        return value;
    }
    return value.back() + reverseString(value.substr(0, value.size() - 1));
}

int main() {
    const std::string original = "Hello, C++!";
    std::cout << reverseString(original) << '\n';
}

Each recursive step creates a substring, so this approach can copy substantial data and make many function calls. Long inputs also require deep call stacks. Prefer reverse iterators or std::reverse in production code unless recursion itself is the subject being taught.

Understand empty strings and character encoding

For an empty string, the reverse-iterator constructor creates another empty string, and the range passed to std::reverse contains no elements. The loop performs no iterations. The recursive example returns at its base case. These approaches therefore need no special output or separate reversal logic for empty input.

A std::string stores char elements, not abstract Unicode characters. With UTF-8 text, one visible character may occupy several bytes, and a user-perceived character may consist of multiple Unicode code points. Reversing the bytes can corrupt the encoding, while reversing code points can still split a grapheme such as a letter combined with an accent. For multilingual text, decode it and use a Unicode-aware library to reverse the units required by the application, often grapheme clusters.