C++ How To Reverse a String
Reverse a String
Use the reverse() function from the <algorithm> library to reverse a string:
Example
string text = "Hello";
reverse(text.begin(), text.end());
cout << text;
You can also reverse a string with a loop that goes backward:
Example
string text = "Hello";
string reversed = "";
for (int i = text.length() - 1; i >= 0; i--) {
reversed += text[i];
}
cout << reversed;
Explanation:reverse() changes the order of all characters from text.begin() to text.end().
The loop starts at the last character (text.length() - 1) and adds the characters to reversed one by one, from the end to the start.