Reverse a string
Description: Reverse "C++ Rocks".
Hint:
std::reverseis in<algorithm>. A string can also be built fromrbegin()andrend().
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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |