Question

I need to create a program that recursively parses a string into smaller substrings. Every substring is one letter shorter than the previous; once it's at the end it would redisplay the word, but with the first letter sliced off, and then substrings of that.

For example: Given the word 'Slugger' the program would display

Slugger
Slugge
Slugg
Slug
Slu
Sl
S
lugger
lugge
lugg
lug
lu
l

And on and on.

This is part of my code so far that is supposed to break things up:

private static void stringParser(String str)
{
    if(str.length() < 1)
    {
        return;
    }
    else if(str.length() == 0)
    {
        removeFirstChar(str, 1);
    }
    else
    {
        System.out.println(str);
        stringParser(str.substring(0, str.length() - 1));
    }
}   // End stringParser method

private static void removeFirstChar(String str, int i)
{
    String strNew = str.substring(i);
    stringParser(strNew);
    return strNew;
}   // End removeFirstChar method

I think I've got all the pieces and parts that I need, but perhaps just don't have them in the right order to do what I want.

Any help is greatly appreciated. Thank you!

Was it helpful?

Solution

I have added the following in your code. See if this works

public static void main(String[] args) {
    String str = "slugger";

    for(int i=0;i<str.length();i++) {
        stringParser(str.substring(i)); 
    }


    }

Complete code.....

public class Test {

    public static void main(String[] args) {
    String str = "slugger";

    for(int i=0;i<str.length();i++) {
        stringParser(str.substring(i)); 
    }


    }

    private static void stringParser(String str)
    {
        if(str.length() < 1)
        {
            return;
        }
        else if(str.length() == 0)
        {
            removeFirstChar(str, 1);
        }
        else
        {
            System.out.println(str);
            stringParser(str.substring(0, str.length() - 1));
        }
    }   // End stringParser method

    private static void removeFirstChar(String str, int i)
    {
        String strNew = str.substring(i);
        stringParser(strNew);
        str = strNew;
    } 

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top