Home > Software engineering >  Making a copy of a string recursively
Making a copy of a string recursively

Time:12-04

I'm learning recursion for my intro computer science class and I'm really struggling with applying it. If I have some method like this:

public static String buildString(String str) {
    ...
    return ...;
}

How would I go about making and returning a copy of the String in the prototype by recursively calling buildString without using an iterator? I've tried using substring a lot, but I kept getting stackoverflow errors.

Disclaimer: This is not a part of a homework assignment or anything of the sort. It's a hypothetical method that I came up with.

CodePudding user response:

  1. Provide exit condition: if input string is empty, return the empty string.
    Use methods String::isEmpty or String::length

  2. Call buildString recursively using substring and adding a character to the result. Here two implementations are possible: pick up the first or the last character and concatenate the character accordingly.
    Use methods String::charAt or String::substring (two versions).

As this seems to be a self-learning exercise, the code of the solution is not provided.

Please be aware that StackOverflowError is highly possible with the recursion if the input string is large enough.

CodePudding user response:

You probably want to use this.

public static String buildString(String str, int in) {
    if(in == str.length()) return "";
    return str.charAt(in)   buildString(str, in 1);
}

Pass buildString(str, 0) as your input.

  • Related