这是一个递归版本:
void reverse( string& word )
{
if ( word.size() <= 1 ) return;
// Get the string without the first and the last char
string temp = word.substr( 1, word.size() - 2 );
// Reverse it
reverse( temp );
// Recompose the string
word = word.substr( word.size() - 1 ) + temp + word[0];
}
但我真的建议您继续使用迭代版本:
// No need to explain, pretty clear
void reverse(string& word)
{
unsigned int end = word.size() - 1;
for ( unsigned int i = 0; i < end; i++, end-- )
{
char c = word[end];
word[end] = word[i];
word[i] = c;
}
}
两者都有的例子。
就像建议的 syam使用 std::reverse
一样:
std::reverse(str.begin(), str.end());