Reverse a string

Description: Reverse "C++ Rocks".

Hint:

  • std::reverse is in <algorithm>. A string can also be built from rbegin() and rend().

Solution

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

int main() {
    std::string s = "C++ Rocks";

    std::string a;
    for (int i = static_cast<int>(s.size()) - 1; i >= 0; i--) a += s[i];

    std::string b = s;
    std::reverse(b.begin(), b.end());

    std::string c(s.rbegin(), s.rend());
    std::cout << a << '\n' << b << '\n' << c << '\n';
}
Output

skcoR ++C
skcoR ++C
skcoR ++C

How it works

  • The three ways give the same result. The library way is the shortest and the clearest.

Read C++ Strings.


Learn more about the similar topics:
Tutorials
C++ Strings: std::string and string_view
C++ Arrays and std::array
C++ Vectors (std::vector)
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Find the second largest number in a vector
Sort a vector with bubble sort
Transpose a matrix
Interview Questions & Answers
What is the difference between an array and a vector in C++?
What is the difference between std::string and a char array in C++?