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);
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);
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();
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));
You might could do something like this as well, even though it is maybe not as pretty as the solution above:
String S;
int Array[]= new int[S.length()];
int Counter=0;
for(int i=0; i<S.length(); i++){
if(Character.isDigit(S.charAt(i))==true){
Array[Counter]=Integer.parseInt(S.charAt(i)+"");
Counter++;
}
}
Downside to is, that you will have an array that is partly empty, if the String is not entirely consisting out of digits. Depending on what you use the array for, you might want to use something else.
If you want an Integer[]
array instead of int[]
use:
String input = "19 35 91 12 36 48 59";
String[] array = input.split(" ");
Integer[] result = Stream.of(array).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);