Search code examples
javarecursionreverse

Reverse String at a specific Index using Recursion


How would I go about making it reverse the string at a specific index for example, goodbye at i=1 would be ybdoog and i=2 is bdoog. Anything before that index is just ignored in the returning string. In Java

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

Solution

  • 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