0

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.

1
  • If you're using recursion, I don't think you'll want to use streams. Commented Mar 23, 2020 at 20:48

2 Answers 2

1

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)));

    }
Sign up to request clarification or add additional context in comments.

Comments

0

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)));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.