Reverse String at a specific Index using Recursion

You need to return s.substring(i) instead of s because you want the reversed substring starting from i. Also, for this, the terminating condition should be if (s == null || s.length() <= i).

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(revStr("goodbye", 2));
        System.out.println(revStr("goodbye", 1));
        System.out.println(revStr("goodbye", 0));
    }

    public static String revStr(String s, int i) {
        if (s.length() <= i)
            return s.substring(i);
        else
            return revStr(s.substring(1), i) + s.charAt(0);
    }
}

Output:

bdoog
ybdoog
eybdoog

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top