Eli Dinkelspiel
Eli Dinkelspiel

Reputation: 779

How to print (but not return) a String recursively using Java?

I hate to abuse SO for homework but I'm in a pickle. Basically, my instructor wants me to do this:

Write a recursive method to print a String backwards.

After that, they want me to do the same thing but have the print statement after the call.

I'm stumped. I already whipped up a normal-person recursive method:

public static String reverseString(String input) {
        if(input.equals("")) {
            return input;
        }
        else {
            return(reverseString(input.substring(1)) + input.substring(0, 1));
        }
}

But the print stuff has me scratching my head. Thanks in advance!

Upvotes: 1

Views: 3508

Answers (3)

Billydan
Billydan

Reputation: 485

if I understand well you should print a "reverse" string using recursive call, if so, use for the first question:

public static void reverseString ( String input ) {
    if ( input != null ) {
        if ( input.length () <= 1 ) {
            System.out.print ( input );
        }else{
           System.out.print ( input.charAt ( input.length ()-1 ));
           reverseString ( input.substring ( 0, input.length ()-1) );
        }
    }
}

and for the second question

 public static void reverseString ( String input ) {
    if ( input != null ) {
        if ( input.length () <= 1 ) {
            System.out.print ( input );
        }else{
           reverseString ( input.substring ( 1, input.length ()) );
           System.out.print ( input.charAt ( 0 ));
        }
    }
}

Upvotes: 0

SomeJavaGuy
SomeJavaGuy

Reputation: 7357

To answer the other alternative. You have to do the same basicly, despite that you need to keep in mind that you do print before doing the recursive call. Due to this you have to print the last letter before doing the recursive call, compared to the other solution from @Eran, where you print the first one.

private static void printBackwards2(String input) {
    if (input.equals("")) {
        return;
    } else {
        // Print the last char
        System.out.print(input.substring(input.length()-1, input.length()));
        // Recursive call without the last char by using substring
        printBackwards2(input.substring(0,input.length()-1));
    }
}

Upvotes: 0

Eran
Eran

Reputation: 394116

Just print whatever you are currently concatenating to the String :

public static void reverseString(String input) {
    if(input.equals("")) {
        return;
    }
    else {
        reverseString(input.substring(1));
        System.out.print(input.charAt(0));
    }
}

or shorter :

public static void reverseString(String input) {
    if(input.length() > 0) {
        reverseString(input.substring(1));
        System.out.print(input.charAt(0));
    }
}

Upvotes: 7

Related Questions