[Solved] How to use recursion to reverse text? [closed]


Normally with recursion you’d have a function that calls itself. You don’t need recursion to reverse a string, but I suppose you could have a function that takes a string, and appends the first character of the string to the reverse of the rest.

I’ll try to explain how this works without giving too much code.

So say you had a function reverse that reverses a string. In it you could say something like:

return reverse(myString.substring(1)) + myString[0];

When you call it on the string Hello, it works like this:

reverse("Hello")
-> reverse("ello") + "H"
-> reverse("llo") + "e" + "H" 
-> reverse("lo") + "l" + "e" + "H" 
-> reverse("o") + "l" + "l" + "e" + "H" 
-> "o" + "l" + "l" + "e" + "H"

It needs to cut off the recursion when the string is empty.

17

solved How to use recursion to reverse text? [closed]