Recursive method to return substring enclosed in characters

118 views Asked by At

I can't use other methods or add parameters and can only call the method recursively. I can't really understand how to approach this problem. I am struggling a bit wrapping my mind around recursion so bare with me.

The substring will be enclosed between the characters first and last. Can someone please guide me? Aside from my base case I know what I have down is not right..I feel like I don't completely understand what is going on at each step.

public static String theSub(String str, char first, char last) {
    if (str.length() == 0 ) {
        return str;
    }
    else if (str.charAt(0)==first) {
        return str.substring(1, str.length() - 1);
    }
  //infinite recursion..
    return theSub(str,first,last);
}
2

There are 2 answers

0
Reilas On

"... The substring will be enclosed between the characters first and last. Can someone please guide me? Aside from my base case I know what I have down is not right..I feel like I don't completely understand what is going on at each step. ..."

For example, if the string is "f(f(f(x)))", and you want to get x.

Essentially, while both first and last are present, get the substring and make a recursive call.

public static String theSub(String str, char first, char last) {
    if (str.length() == 0 ) return str;
    int i = str.indexOf(first), j = str.lastIndexOf(last);
    if (i == -1 || j == -1) return str;
    return theSub(str.substring(i + 1, j), first, last);
}
0
Sarah On

I'll walk you through the steps to create a recursive method that extracts the substring enclosed between the characters first and last.

public static String theSub(String str, char first, char last) {
    // Base case 1: If the input string is empty, return an empty string.
    if (str.length() == 0) {
        return "";
    }

    // Base case 2: If the first character of the string is 'last', return an empty string.
    if (str.charAt(0) == last) {
        return "";
    }

    // Base case 3: If the first character of the string is 'first', call the helper function.
    if (str.charAt(0) == first) {
        return extractSubstring(str.substring(1), first, last);
    }

    // Recursive case: Keep looking for the 'first' character.
    return theSub(str.substring(1), first, last);
}

// Helper function to extract the substring between 'first' and 'last' characters.
private static String extractSubstring(String str, char first, char last) {
    // Base case: If the string is empty, return an empty string.
    if (str.length() == 0) {
        return "";
    }

    // If the current character is 'last', we've reached the end of the substring.
    if (str.charAt(0) == last) {
        return "";
    }

    // Recursively build the substring.
    return str.charAt(0) + extractSubstring(str.substring(1), first, last);
}

This should allow you to correctly extract the substring enclosed between first and last characters using recursion.