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?

1
  • 1
    thanks for the editing. I will get it right some day. ;) Commented Apr 10, 2013 at 14:14

6 Answers 6

9

Try

char[] chars = strNumbers.toCharArray();

and then iterate through the char array.

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

1 Comment

This is a good idea, I feel a bit stupid because I did not think of that.
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.

2 Comments

This is exactly what I was looking for. Thank you very much. I am kind of new to regex but I am getting there.
You're welcome :) I can recommend this site as a good regex reference site.
1

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

Comments

0

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

Comments

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

Comments

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.

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.