Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading