Reverse a String using Recursion

Objective: Given a String, write a recursive program to reverse it.

Example:

Original String: tutorial horizon
Reversed String: noziroh lairotut

Approach:

  • Take the first character out of the string, add it to the end of result of the remaining string.
  • Make a recursive call to remaining string.

Java Code:

public class ReverseString {
public String reverse(String input){
if(input.isEmpty())
return input;
//else put the character at the beginning to the end
//make a recursive call
return reverse(input.substring(1))+input.charAt(0);
}
public static void main(String[] args) {
ReverseString r = new ReverseString();
String input = "tutorial horizon";
String reversedString = r.reverse(input);
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + reversedString);
}
}

view raw
ReverseString.java
hosted with ❤ by GitHub

Output:

Original String: tutorial horizon
Reversed String: noziroh lairotut