How to recursively print out each character one at a time in a String function

I am trying to get better at understanding recursive features through the usage of String functions. I am trying to create a function that recursively prints out one char at a time until the stack reaches the end of the String. For example the input would look like this:

String str = "Hi";
//Output:
H
i

I have been practicing recursion using Int functions, and have been slowly trying to ease my way into understanding recursion using String functions. I am confused on how exactly to call the function to increase or decrease. With Int functions it's easy to do using this methodology.

int function(int N){
    return function(N+1);
}

Here is the current code I have.

String str = "Hi";

public String forward(String str){
    if(str.equals(null) || str.length()<2) return str;

    System.out.println(str.charAt(0));
    return forward(str.substring(0, str.length()-1));
}

The expected output should be:

H
i

But instead the current output is:

H
H

Thank you for your time and patience, any assistance or guidance is greatly appreciated.


Solution 1:

Because you are recursing with the same String every time. You want to actually skip the first character. And you don't need to return anything. And the method should be static. And don't use Object.equals(null) - that would give you a NullPointerException on null. Something like,

public static void forward(String str) {
    if (str == null || str.isEmpty()) {
        return;
    }
    System.out.println(str.charAt(0));
    forward(str.substring(1));
}

Outputs

H
i

Solution 2:

In order to create a recursive method, you have to implement two crucial parts of recursive logic: BASE CASE and RECURSIVE CASE.

Base case - is represented by the input for which result is known in advance. In this case, it's the end of the string.

Recursive case - is where your logic resides, and where recursive calls are made.

    public static void main(String[] args) {
        printStr("test");
    }

    public static void printStr(String str) {
        if (str.isEmpty()) return;
        helper(str, 0);
    }

    private static void helper(String str, int i) {
        if (i >= str.length()) return;
        System.out.println(str.charAt(i));
        helper(str, i + 1);
    }

Solution 3:

A recursive function calls itself from within the same function. The function needs to have a way to escape eventually or there would be a StackOverFlowError.

public static void main(String[] args) {
  printStr("Hi");
}

private static String printStr(String s) {
  if (s == null || s.length() == 0) {
    return null;
  }
  System.out.println(s.charAt(0));
  return s.length() >= 1 ? printStr(s.substring(1)) : null;
}