The short answer: swap from both ends
To flip a string backwards, swap its first character with its last, then the second with the second-to-last, and keep going until you reach the middle:
#include <cstddef>
#include <iostream>
#include <string>
#include <utility>
int main() {
std::string word = "stressed";
for (std::size_t i = 0; i < word.size() / 2; ++i) {
std::swap(word[i], word[word.size() - 1 - i]);
}
std::cout << word << "\n"; // desserts
}
Each pass moves one pair of characters into their mirror positions. “stressed” has eight characters, so there are four pairs and four swaps. The result is “desserts”.
Build the reversed text from the end
You can also read the string from the last character to the first and add each one to a new string:
std::string word = "stressed";
std::string flipped;
for (std::size_t i = word.size(); i > 0; --i) {
flipped += word[i - 1];
}
std::cout << flipped << "\n"; // desserts
This leaves the original string unchanged. The index i - 1 keeps every read inside the string.
A shorter route
C++ can build the reversed copy in one line with reverse iterators:
std::string flipped(word.rbegin(), word.rend());
When byte-by-byte reversal is not enough
The swap and the copy both work on plain ASCII text, where each character is one byte. Accented letters and emoji use more than one byte in UTF-8, and reversing bytes can break them apart. The C++ methods, including the standard library call, are compared in how to reverse a string in c.