Reversing Strings

How Do You Reverse a String?

Reversing a string means putting its characters in the opposite order. Here is the idea and a short C++ example that swaps characters from both ends.

On this page
  1. The short answer: swap from both ends
  2. Build the reversed text from the end
  3. A shorter route
  4. When byte-by-byte reversal is not enough

The short answer: swap from both ends

To flip a string backwards, swap its first character with its last, then the second with the second-to-last, and keep going until you reach the middle:

#include <cstddef>
#include <iostream>
#include <string>
#include <utility>

int main() {
    std::string word = "stressed";
    for (std::size_t i = 0; i < word.size() / 2; ++i) {
        std::swap(word[i], word[word.size() - 1 - i]);
    }
    std::cout << word << "\n";  // desserts
}

Each pass moves one pair of characters into their mirror positions. “stressed” has eight characters, so there are four pairs and four swaps. The result is “desserts”.

Build the reversed text from the end

You can also read the string from the last character to the first and add each one to a new string:

std::string word = "stressed";
std::string flipped;
for (std::size_t i = word.size(); i > 0; --i) {
    flipped += word[i - 1];
}
std::cout << flipped << "\n";  // desserts

This leaves the original string unchanged. The index i - 1 keeps every read inside the string.

A shorter route

C++ can build the reversed copy in one line with reverse iterators:

std::string flipped(word.rbegin(), word.rend());

When byte-by-byte reversal is not enough

The swap and the copy both work on plain ASCII text, where each character is one byte. Accented letters and emoji use more than one byte in UTF-8, and reversing bytes can break them apart. The C++ methods, including the standard library call, are compared in how to reverse a string in c.

The complete guide to reversing strings

How to Reverse a String in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

stringstream in C++

stringstream in C++ explained: how the <sstream> classes read and write text in memory, convert strings and numbers, split text, and avoid common mistakes.

stringstream 4 min read

List vs Array in C++

Compare C++ arrays, std::array, std::vector and std::list by memory layout, element access and insertion cost, with code and a simple rule for choosing.

List vs Array 5 min read