Bryozoa Bryozoa - 1 month ago 9
Java Question

Is it possible to make an int array from string of digits in one line?

I have a string of digits which I want to convert to an array of int digits. I am new to Java and not very good at standart methods. I could write a multiline algorithm with for statements but I'm sure there's a better solution with built in methods. I came up with these lines:

strng.getChars(0, strng.length(), chArr = new char[strng.length()], 0);
Character.digit(chArr);


I tried to put these lines together, but getChars is void and Character.digit is not applicable with void. So I stuck here. Is there any way to make an int array from string of digits in one nice line?

Answer

Assuming that you have only digits in your String, you could proceed as next using the Stream API:

String input = "0123456789";
int[] result = input.chars().map(i -> i - 48).toArray();
System.out.println(Arrays.toString(result));

Ouptut:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Comments