如果String
的格式类似于"19 35 91 12 36 48 59"
,我想要一个具有相同结构的数组。
我已经尝试过:
array[]=Integer.parseInt(str);
如果String
的格式类似于"19 35 91 12 36 48 59"
,我想要一个具有相同结构的数组。
我已经尝试过:
array[]=Integer.parseInt(str);
int[] result = Arrays.stream(str.split(" ")).mapToInt(Integer::parseInt).toArray();
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));
Integer[]
数组而不是int[]
,请使用以下代码: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);
你也可以像这样做,尽管这个解决方案可能没有上面的解决方案漂亮:
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++;
}
}