64.2k views
2 votes
Write a recursive method public static String reverse(String str) that computes the reverse of a string. For example, reverse("flow") should return "wolf". Hint: Reverse the substring starting at the second character, then add the first character at the end. For example, to reverse "flow", first reverse "low" to "wol", then add the "f" at the end.

User Lizbeth
by
5.2k points

1 Answer

5 votes

Answer:

Step-by-step explanation:

StringRecursiveReversal.java

public class StringRecursiveReversal {

static String reverse1 = "";

public static String reverse(String str){

if(str.length() == 1){

return str;

} else {

reverse1 += str.charAt(str.length()-1)

+reverse(str.substring(0,str.length()-1));

return reverse1;

}

}

public static void main(String a[]){

StringRecursiveReversal srr = new StringRecursiveReversal();

System.out.println("Result: "+srr.reverse("flow"));

}

}

Output :

Result: wolf

User Elias Holzmann
by
5.5k points