Reversing a String

This lesson will teach you how to reverse a string with recursion

What does reverse mean?

When given a string, we can do multiple actions with it. One of these being, reversing a string. By reversing we simply mean, we can take the string and flip it. All the letters in the front, go to the back and vice versa. The illustration below shows exactly how to do that!

Note: Keep in mind that a string can be one word or multiple words.

Implementing the Code

The code below shows how to do this with recursion! First, let’s see the code then we can go on to its explanation.

Try the code by changing the values of sentence and word to see how it works with other strings!

Press + to interact
#include <iostream>
#include <string>
using namespace std;
void reverseString(string &reversee, int index)
{
int n = reversee.length();
if (index == n / 2)
return;
char swap = reversee[index];
reversee[index] = reversee[n-index-1];
reversee[n-index-1] = swap;
reverseString(reversee, index + 1);
}
int main() {
string sentence = "Hello World";
string word = "Hello";
int index = 0;
cout<< "Reversing the sentence: "<<sentence<<endl;
reverseString(sentence, index);
cout<< sentence <<endl;
cout<< "Reversing the word: "<<word<<endl;
reverseString(word, index);
cout<< word<< endl;
}

Unde

...