Manipulating std::string Objects

Reverse String

How can I reverse the contents of a std::string?

Abstract art representing computer programming

Reversing the contents of a std::string can be done easily using standard library functions. Here are a few methods to achieve this.

Using std::reverse

The std::reverse algorithm from the <algorithm> header is the simplest way to reverse a string. For example:

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

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

  std::reverse(Text.begin(), Text.end());

  std::cout << Text;
}
!dlroW ,olleH

Using a Custom Function

You can also write a custom function to reverse a string if you need more control over the process. For example:

#include <iostream>
#include <string>

void ReverseString(std::string& str) {
  size_t n = str.size();
  for (size_t i = 0; i < n / 2; ++i) {
    std::swap(str[i], str[n - i - 1]);  
  }
}

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

  ReverseString(Text);

  std::cout << Text;
}
!dlroW ,olleH

Using Stack

You can use a stack to reverse a string, which might be useful in certain contexts, such as parsing algorithms. For example:

#include <iostream>
#include <string>
#include <stack>

int main() {
  std::string Text{"Hello, World!"};
  std::stack<char> Stack;

  for (char c : Text) {
    Stack.push(c);
  }

  std::string Reversed;
  while (!Stack.empty()) {
    Reversed += Stack.top();
    Stack.pop();  
  }

  std::cout << Reversed;
}
!dlroW ,olleH

Using Iterators

If you prefer using iterators, you can construct a reversed string using reverse iterators. For example:

#include <iostream>
#include <string>

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

  std::string Reversed(
    Text.rbegin(), Text.rend()
  );  

  std::cout << Reversed;
}
!dlroW ,olleH

Considerations

  • Performance: std::reverse is the most efficient method for most use cases.
  • Readability: Custom functions and iterators can make the code more readable and understandable for specific needs.

By using these techniques, you can easily reverse the contents of a std::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