Reversing Strings

Does reverse() Work on Strings?

Yes, std::reverse works on std::string in C++, but std::string has no reverse() member. Learn how the call works and the common mistakes to avoid.

On this page
  1. The short answer
  2. Calling std::reverse
  3. Don’t assign the result
  4. Qualify the name
  5. C-style arrays and C++20

The short answer

Yes. std::reverse works on std::string. The one thing to avoid is calling reverse() as a member, because std::string has no member function with that name. text.reverse() does not compile.

Calling std::reverse

Pass std::reverse the iterators for the start of the string and one past its end. It changes the string in place:

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

int main() {
    std::string text = "learn";
    std::reverse(text.begin(), text.end());
    std::cout << text << "\n";  // nrael
}

Don’t assign the result

std::reverse returns nothing, so you cannot store its result. This line does not compile:

std::string flipped = std::reverse(text.begin(), text.end());  // does not compile: returns void

If you want a reversed copy, build one from the reverse iterators instead, and leave the original alone:

std::string flipped(text.rbegin(), text.rend());  // "nrael"; text is unchanged

Qualify the name

Write std::reverse rather than a bare reverse. The qualified name shows where the function comes from, and a bare name can match other functions that share it.

C-style arrays and C++20

std::reverse also works on a char array, using pointers as the start and end. The array must be writable.

C++20 added a version that takes the whole range at once: std::ranges::reverse(text); changes the string in place, the same as the iterator version.

The complete guide to reversing strings

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

Keep exploring

Guides from other topics

All topics →