0

I am trying to use a recursive method to change strings to char arrays but i am getting an error

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(Unknown Source)

I want to solve this problem only using recursive method(not loop or toChar method)

public class Recur {
    public char[]  stringTochar(String str)
    {
        if (str != null && str.length() > 0)
        {
            System.out.println(str.charAt(0)) ;
            stringTochar(str.substring(1)); 
        }
        return stringTochar(str.substring(1)) ;
    }
}

public class Tester {
    public static void main(String[] args) {
        Recur recur= new Recur ();
        recur.stringTochar("this is a test");
    }
}
8
  • Why are you trying to reinvent String#toCharArray, and in particular, why reinvent it using recursion? Commented Feb 10, 2013 at 15:24
  • @T.J.Crowder learning purposes. Commented Feb 10, 2013 at 15:25
  • 1
    Your base case also calls the recursive function instead of stopping. Commented Feb 10, 2013 at 15:25
  • Similar to this stackoverflow.com/questions/4633297/… Commented Feb 10, 2013 at 15:26
  • 1
    @ buni: This problem is particularly poorly-suited to being solved with recursion. If you want to learn about recursion, I suggest a different task, such as (say) traversing a tree structure. The problem being that a recursive task must build up its results incrementally, which is difficult to do with a char[] return type. Commented Feb 11, 2013 at 12:29

2 Answers 2

4
str.substring(1);

What happens when str is length 0?

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

Comments

1
public class Recur
{
    private static char [] stringToChar (
        String str, char [] destination, int offset)
    {
        if (destination == null)
        {
            destination = new char [str.length ()];
            offset = 0;
        }

        if (offset < str.length ())
        {
            destination [offset] = str.charAt (offset);
            stringToChar (str, destination, offset + 1);
        }
        return destination;
    }

    public static void main (String [] args)
    {
        char [] chars = stringToChar ("this is a test", null, 0);

        for (char c: chars)
            System.out.println (c);
    }
}

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.