1

I have a long string of numbers,

String strNumbers = "123456789";

I need to get an int[] from this.

I use this method to get it:

public static int[] getIntArray(strNumbers)
{
    String[] strValues = strNumbers.split("");
    int[] iArr = new int[strValues.length];
    for(int i = 0; i < strValues.length; i++)
    {
        iArr[i] = Integer.parseInt(strValues[i]);
    }
    return iArr;
}

I get this error : java.lang.NumberFormatException: For input string: ""

My guess is that I cannot split a String that way. I tried all sorts of escape or Regex but nothing works.

Can anyone help?

4

6 回答 6

9

Try

char[] chars = strNumbers.toCharArray();

and then iterate through the char array.

于 2013-04-10T14:02:45.240 回答
6

Your problem is the split regex. Try this instead:

String[] strValues = strNumbers.split("(?<=\\d)");

This splits after every digit (using a look behind regex), which will create an array of size zero for blank input.

于 2013-04-10T14:07:36.260 回答
1

You can use charAt() function to retrieve each character in the string and then do the parseInt()

于 2013-04-10T14:03:36.420 回答
0

You could simply use a for loop going through your string and calling String.charAt(int)

于 2013-04-10T14:03:42.723 回答
0

Try:

char[] chars = strNumbers.toCharArray();
int[] iArr = new int[chars.length];
for(int i = 0 ; i < chars.length ; ++i) {
    iArr[i] = chars[i] - '0';
}
于 2013-04-10T14:05:31.253 回答
0

You can use a loop statement to iterate the string. And then you use a substring method to chop the string into individual number. Using the substring() method you can define the length of the substring to be converted into number.

于 2013-04-10T14:05:37.917 回答