How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?
Here is the cleanest, safest, easiest way to reverse a string in C++ (in my opinion):
#include
void swap(std::string& str, int index1, int index2) {
char temp = str[index1];
str[index1] = str[index2];
str[index2] = temp;
}
void reverse(std::string& str) {
for (int i = 0; i < str.size() / 2; i++)
swap(str, i, str.size() - i - 1);
}
An alternative is to use std::swap
, but I like defining my own functions - it's an interesting exercise and you don't need to include
anything extra.