I am attempting to use recursion to reverse a string but the special twist is that I must start at a specified index return that character contained at the index and then reverse the remaining string after that index and combine the two into one output. I have tried to do this and sometimes it gives an array out of bounds exception and sometimes ends up with more letters than it should have such as this test of helloooo coming out as lloooooo. Any help with tweaking this code would be appreciated as I became really lost when the need for the second parameter was known to me.
public class ReverseTest
{
public static void main(String[] argv)
{
System.out.println(reverse("a", 0));
System.out.println(reverse("hi", 0));
System.out.println(reverse("helloooo", 2));
}
public final static String reverse(String s, int ind)
{
int length = s.length(); //get string length
if (length <= 1) //if length is 1 or lower just repeat the string nothing to do
return s; //return string
else //if we have something to work with...
return s.substring(ind) + reverse(s.substring(ind + 1, length - 1), ind); //return substring of necessary index + reverse the rest and display in one string
}
}
Not sure what is wrong with your version, but I built my own according to what I find to be an intuitive implementation: