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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Output:
Original String: tutorial horizon Reversed String: noziroh lairotut