dancingbush
dancingbush

Reputation: 2281

How to use use recursion to return an array of substrings

I am trying to break a string down into substrings of size 3, and convert each substring into an array of strings, and return the final array recursively.

So far I have the following:

 private static String[] substrings(String string) {

    // base case
    if (string.length() <= 3) return new String[] { string };


            // this will return 
           return (Stream.concat(Arrays.stream(new String[]{string.substring(0,3)}), Arrays.stream(new String[] {string.substring(3)})).toArray(String[]::new));



        }

How would you call the last function recursively and how I would merge the String substrings recursively.

Any input appreciated.

Upvotes: 0

Views: 262

Answers (2)

smac89
smac89

Reputation: 43078

I believe this is what you were trying to do:

private static String[] substrings(String string) {

    // base case
    if (string.length() <= 3) {
        return new String[] { string };
    }

    // this will return 
    return Stream.concat(Stream.of(string.substring(0, 3)),
      Arrays.stream(substrings(string.substring(3))).toArray(String::new);
}

This is quite wasteful because it creates a lot of arrays as the recursion unwinds.

You can fix this by having it return Stream instead:

private static Stream<String> substrings(String string) {

    // base case
    if (string.length() <= 3) {
        return Stream.of(string);
    }

    // this will return 
    return Stream.concat(Stream.of(string.substring(0, 3)), substrings(string.substring(3)));
}

Upvotes: 0

bob tang
bob tang

Reputation: 593

is this what you are after? ArrayUtils.addAll() is from apache common lang library.

Although i don't think it is very intuitive and efficient. iterative way is preferred.

    String[] substrings(String string){
        //exist condition
        if (string.length() <= 3) return new String[] { string };
        //get the substrings recursively
        String first = string.substring(0,3);
        return ArrayUtils.addAll(new String[] { first }, substrings(string.substring(3)));

    }

Upvotes: 1

Related Questions