I already wrote something that removes the first character of a string and puts it after the remaining substring and then prints it out, the instructions were to reverse the sentence using recursion by removing the first letter of the sentence and concatenate it to the reversed remaining substring, ie. “Hello” yields “olleH”. But i dont know about the recursion part, any help would be appreciated, thanks. This is my code:
public class Sentence {
private String sentence;
public Sentence(String astring) {
sentence = astring;
}
public void reverse(){
String firstChar = sentence.substring(0,1);
String remainingSen = sentence.substring(1,sentence.length());
System.out.println(remainingSen+firstChar);
}
}
Do you understand the concept of recursion? If so, figure out the base case (the condition that would stop the recursion) and what you want to do in each recursive step. Hint: you’ll need a recursive method that takes the string to be reversed and returns the reversed string. Not going to straight up answer a HW question, but that should get you started.
EDIT: (One more hint) don’t try to make the void reverse() method recursive. Have it call a different, private recursive method that actually does the reversing.