priyank
priyank

Reputation: 35

How to split string of numbers in to int array?

How to split string containing numbers into int array i.e

String s="12345";
int i[]=new int[5]; 
i[0]=1; 
i[1]=2;
i[2]=3; 
i[3]=4; 
i[4]=5;

i have tried it by

String s="12345";
int i[]=new int[5];
int tem = Integer.parseInt(s);
for(int t=0;t<5;t++){
i[4-t]=tem%10;
tem=tem/10;
}

it is giving right answer in above case but in case of String s="73167176531330624919225119674426574742355349194934" it fails so any other way or how to use split method in above case

Upvotes: 0

Views: 15973

Answers (4)

Amit Das
Amit Das

Reputation: 1107

You can simple use Character wrapper class and get the numeric value and add it to array of in.

        String sample = "12345";

        int[] result = new int[sample.length()];

        for(int i=0;i<result.length;i++)
        {
            result[i] = Character.getNumericValue(sample.charAt(i));
        }

Upvotes: 0

stanga bogdan
stanga bogdan

Reputation: 724

You can use Character.getNumericValue(char)

String str = "12345";
int[] nums = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
    nums[i] = Character.getNumericValue(str.charAt(i));
}

Upvotes: 6

SMA
SMA

Reputation: 37023

That's because your number wont fit in the integer range nor in long range. Also to note, Your code wont be that efficient due to division and modulas operator as well. Instead you could always use charAt api of String and convert individual characters to a number as give below:

String s = "73167176531330624919225119674426574742355349194934";
int[] numbers = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
   numbers[i] = s.charAt(i) - '0';
}
System.out.println(Arrays.toString(numbers));
Output:
[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9, 2, 2, 5, 1, 1, 9, 6, 7, 4, 4, 2, 6, 5, 7, 4, 7, 4, 2, 3, 5, 5, 3, 4, 9, 1, 9, 4, 9, 3, 4]

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213263

The culprit is this line of code:

int tem = Integer.parseInt(s);

When you enter a large number is string which is outside the range of what an int can accomodate, the overflow happens, and thus all of a sudden you are working on a different number than what was in your string.

I would suggest you iterate over each character of the string, and then convert each character to integer:

for (char ch: s.toCharArray()) {
    // convert ch to integer, and add to the array.
    intArray[i] = (int)(ch - '0');
    // of course keep incrementing `i`
}

Upvotes: 1

Related Questions