How to Reverse C++ Strings

Here is a method to reverse output a C++ string:

#include <iostream>
#include <string>
using namespace std;

void reverseString(string str) {
    int length = str.length();
    for (int i = length - 1; i >= 0; i--) {
        cout << str[i];
    }
    cout << endl;
}

int main() {
    string str = "Hello World!";
    reverseString(str);
    return 0;
}

When running the code above, the output will be “!dlroW olleH”, which means reversing the string. In the reverseString function, it iterates through the string starting from the last character and outputs each character in sequence.

bannerAds