A Deeper Look at the std::string Class

Reversing a String in C++

What's the most efficient way to reverse a std::string?

Abstract art representing computer programming

Reversing a std::string is a common operation that can be accomplished efficiently using the standard library. Here's a look at a few methods, starting with the most straightforward and efficient:

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

std::string reverse_string(std::string str) {
  std::reverse(str.begin(), str.end());  
  return str;
}

int main() {
  std::string text{"Hello, World!"};

  std::cout << "Original: " << text << '\n';
  std::cout << "Reversed: "
    << reverse_string(text) << '\n';

  // In-place reversal
  std::reverse(text.begin(), text.end());  
  std::cout << "Reversed in-place: "
    << text << '\n';
}
Original: Hello, World!
Reversed: !dlroW ,olleH
Reversed in-place: !dlroW ,olleH

The std::reverse() function from the <algorithm> header is the most efficient way to reverse a std::string. It works in-place, modifying the original string, and has a time complexity of O(n/2)O(n/2), where nn is the length of the string.

If you need to preserve the original string, you can create a copy first:

std::string reverse_string(const std::string& str) {
  std::string reversed{str};
  std::reverse(reversed.begin(), reversed.end());
  return reversed;
}

For educational purposes, here's how you might implement string reversal manually:

std::string manual_reverse(
  const std::string& str
) {
  std::string reversed;
  // Preallocate space
  reversed.reserve(str.length());
  for (
    auto it = str.rbegin();
    it != str.rend();
    ++it
  ) {
    reversed.push_back(*it);
  }
  return reversed;
}

This manual method is less efficient than std::reverse() but demonstrates the concept clearly.

For Unicode strings, simple reversal might not work correctly due to multi-byte characters and combining characters. In such cases, you'd need a more sophisticated approach or a Unicode-aware library.

Remember, when working with std::string, it's often more efficient to modify the string in-place rather than creating a new string for each operation. The in-place reversal using std::reverse() is typically the most efficient method for reversing a string in C++.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved