Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String into an Integer[] array in Java? [duplicate]

If the String is something like "19 35 91 12 36 48 59" and I want an array of the same structure.

I already tried

array[]=Integer.parseInt(str);
like image 248
Alex_70 Avatar asked Dec 11 '22 04:12

Alex_70


2 Answers

I'd split the string, stream the array, parse each element separately and collect them to an array:

int[] result = Arrays.stream(str.split(" ")).mapToInt(Integer::parseInt).toArray();
like image 188
Mureinik Avatar answered Dec 21 '22 22:12

Mureinik


if they are separated by spaces you can convert them one by one like this

String array = "19 35 91 12 36 48 59";
// separate them by space
String[] splited = array.split(" ");
// here we will save the numbers
int[] numbers = new int[splited.length];
for(int i = 0; i < splited.length; i++) {
    numbers[i] = Integer.parseInt(splited[i]);
}
System.out.println(Arrays.toString(numbers));        
like image 44
elbraulio Avatar answered Dec 21 '22 22:12

elbraulio