Reputation: 12375
I have a String of this kind
String s=1956;
and want to convert this String
in int[]
array
[1,9,5,6];
Any suggestion?
Upvotes: 0
Views: 1856
Reputation: 1073
I'm going to provide a the most possible simple solution to this;
String s = "1956";
int array[] = new int[4];
array[0] = Integer.parseInt(s.charAt(0)+"");
array[1] = Integer.parseInt(s.charAt(1)+"");
array[2] = Integer.parseInt(s.charAt(2)+"");
array[3] = Integer.parseInt(s.charAt(3)+"");
Obviously loops can do this, but you really didn't tell us the context of your situation
Upvotes: 0
Reputation: 59096
I would do it like this:
int[] digits = new int[s.length()];
for (int i = 0; i < digits.length; ++i) {
digits[i] = s.charAt(i)-'0';
}
I could never bring myself to use Integer.parseInt(String)
just to translate a digit character into an integer.
Upvotes: 1
Reputation: 23016
You can use the split
method of String
to convert it to a String[]
, and then you can iterate over it calling Integer.parseInt
to populate a int[]
Upvotes: 1
Reputation: 35598
One option would be
char[] nums = s.toCharArray();
int[] parsed = new int[nums.length];
for (int i = 0; i < nums.length; ++i){
parsed[i] = Integer.parseInt(String.valueOf(nums[i]));
}
Upvotes: 0