Recursive String Reversal
Reverse a string using recursion
/* Exercise: Recursive String Reversal Coder: ttg Date: 2/7/24 The main method is supplied; write the necessary code to get the program to work as described. */ import java.util.Scanner; public class StringReverseDriver{ //no-touch main method public static void main(String[] args){ public static void main(String[] args){ String msg = "I love Computer Science!"; System.out.println(msg); System.out.println(); String rev1 = reverse(msg); System.out.println("rev1:\n" + rev1); System.out.println(); msg = "Recursion is tricky!"; String rev2 = reverseByRecursion(msg, msg.length()-1); System.out.println("rev2:\n" + rev2); }//end main method public static String reverse(String str){ String temp = ""; for(int ndx = str.length()-1; ndx >= 0; ndx--){ String symbol = str.substring(ndx, ndx+1); temp += symbol; } return temp; }//end reverse public static String reverseByRecursion(String str, int ndx){ if(ndx < 0){ //base case return ""; }else{ return str.substring(ndx, ndx+1) + reverseByRecursion(str, ndx-1); } }//end method reverseByRecursion }//end class StringReverseDriver