How to convert integer to a char array or integer array

Asked

Viewed 382 times

0

Scanner key = new Scanner(System.in);
int num = key.nextInt();

Assuming one is 100, how to convert one to an array of char where:

char[0] == '1'
char[1] == '0'
char[2] == '0'

Or convert to an integer array where:

int[0] == 1
int[1] == 0
int[2] == 0

1 answer

1


You can do this in several modes, the simplest would be to convert your number to a String and then apply the method toCharArray, example:

int num = 100; // Seu numero
String numStr = Integer.toString(num); // Converte o mesmo em uma String
char numArr[] = numStr.toCharArray(); // Converte a String em um Array de chars

If you would like to have an Array of integers, you can do it as follows:

int arrInt[] = numStr.chars().map(c -> Character.getNumericValue((char)c)).toArray();

chars() will return a IntStream which can be carried forward through the method map() and within this we convert again each String character value into an integer by applying the method getNumericValue, once iteration is completed, the method toArray is called to convert the stream an array, which in your case will be an integer array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.