0

我正在尝试使用递归方法将字符串更改为 char 数组,但出现错误

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

我只想使用递归方法(不是循环或 toChar 方法)来解决这个问题

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

2 回答 2

4
str.substring(1);

str长度为 0 时会发生什么?

于 2013-02-10T15:24:43.467 回答
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);
    }
}
于 2013-02-10T15:30:20.470 回答