I would just like to ask how to convert an int to int array - for example: int number = 12345; to: [1,2,3,4,5]; Btw - could not really find anything out there, so we may hope that someone know. thanks in advance
Asked
Active
Viewed 177 times
-1
-
6Does this answer your question? [Convert an integer to an array of digits](https://stackoverflow.com/questions/8033550/convert-an-integer-to-an-array-of-digits) – maloomeister Feb 17 '21 at 12:40
-
The following links may also be helpful: [how to split an integer into digits and square each number](https://stackoverflow.com/questions/37096700/java-how-to-split-an-integer-into-individual-digits-and-then-square-each-numbe), [scramble each digit of the int and print out the biggest possible integer](https://stackoverflow.com/questions/64125767/scramble-each-digit-of-the-int-a-and-print-out-the-biggest-possible-integer/) – Nowhere Man Feb 17 '21 at 12:50
1 Answers
0
You can do it like this:
int number = 12345;
int[] digits = String.valueOf(number).chars().map(c -> c-'0').toArray();
Explanation:
First convert int to string with String.valueOf(number)
to be able to use the method chars()
which get a stream of int that represents the ASCII value of each char in the string. Then, we use the map function map(c -> c-'0')
to convert the ASCII value of each character to its value, subtracting the value of the ASCII code from the character '0' from the ASCII code of the actual character. Finally, the stream is converted to an array with toArray()
.

OneOfAKind_12
- 446
- 5
- 8