W3docs

Convert an integer to an array of digits

To convert an integer to an array of digits in Java, you can use the toCharArray() method of the String class to convert the integer to a string, and then use the toCharArray() method to convert the string to an array of characters.

To convert an integer to an array of digits in Java, you can use the toCharArray() method of the String class to convert the integer to a string, and then use the toCharArray() method to convert the string to an array of characters.

Here is an example of how to do this:


int number = 12345;
char[] digits = String.valueOf(number).toCharArray();

In this example, the String.valueOf() method is used to convert the integer to a string, and the toCharArray() method is used to convert the string to an array of characters. The resulting digits array will contain the character representations of the digits in the order they appear. If you need an array of integers for mathematical operations, you can convert it using a stream:

int[] intDigits = Arrays.stream(digits).map(c -> c - '0').toArray();

Note that String.valueOf() includes a minus sign for negative numbers. If you only want the numeric digits, use Math.abs(): String.valueOf(Math.abs(number)).toCharArray().

You can also use the String.split() method to split the string into an array of strings, each containing a single digit:


int number = 12345;
String[] digits = String.valueOf(number).split("(?<=.)");

In this example, the split() method is called with a zero-width positive lookbehind (?<=.) as the delimiter. This splits the string after each character, correctly producing an array of single-character strings without a leading empty string.

For better performance and readability, toCharArray() is generally preferred over regex-based splitting.

I hope this helps. Let me know if you have any questions.