Bryozoa Bryozoa - 1 year ago 100
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);

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 Source

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();


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download