Ben Nutter
Ben Nutter

Reputation: 1

Java recursive method to print one word in a string at a time without loops

For this program, the idea is to print one word in a string at a time using a recursive method, assuming that there is only one word between spaces. When I run this program as is, however, it instead prints the string itself.

public static void stringByWords(String s) {


    if (s.isEmpty())

        return;

    if (s.indexOf(" ") == 1)

     stringByWords(s.substring(s.indexOf(" ") + 1) + "\n");

    System.out.println(s);


}//end stringByWords

I realize it would be a hell of a lot easier to do this as an iterative method with just a loop, but I'm required to use recursion as instructed. Any tips as to what I'm doing incorrectly will be appreciated.

Upvotes: 0

Views: 1392

Answers (2)

Ben Nutter
Ben Nutter

Reputation: 1

Alright, after fixing up my code from the tips I was given, it seems to function as intended. I will put the fixed code here in case it is helpful to someone else. Thanks to those who had helped.

public static void stringByWords(String s) {

    int space = s.indexOf(' ');

    if (s.isEmpty()) //error case

        return;

    if (space == -1) { //base case

        System.out.println(s);
    }
    else { 

        stringByWords(s.substring(0, space));//recursive steps
        stringByWords(s.substring(space + 1));

    }//end else


}//end stringByWords

Upvotes: 0

sprinter
sprinter

Reputation: 27976

The trick with recursion is to follow the standard pattern

func(context)
    if context is very simple
        process context
    else
        break context into several pieces
            call func on each piece

So for your case, the simple situation is a single words with no spaces. Otherwise break into two pieces and call on each piece:

void printWords(String str) {
    int space = str.indexOf(' ');
    if (space == -1) {
        System.out.println(str);
    } else {
        printWords(str.substring(0, space));
        printWords(str.substring(space + 1));
    }
}

Upvotes: 3

Related Questions