我有一个字符串,例如“90 60 90”—— body 比例。我想从字符串中取出 3 个数字并将它们放入 int 数组中。 像这样:
sizes[0] = 90;
sizes[1] = 60;
sizes[2] = 90;
也许有更优雅的方法来解决这个问题,但我只能想出这种方法。如果您能向我展示更优雅的方式或帮助解决此问题,我将很高兴。当 j = 2 且 a = ' ' 时,循环就这样停止。
public class Main {
public static void main(String[] args) {
String[] sizes = {"90 60 90", "90 70 60"};
// int[][] firstNumber = new int[sizes.length][3];
String firstNumber = "";
String secondNumber = "";
String thirdNumber = "";
int spaces = 0;
for (int i = 0; i < sizes.length; i++) {
int length = sizes[i].length();
for (int j = 0; j < length; j++) {
char a = sizes[j].charAt(j);
if (a != ' ' && spaces == 0) {
firstNumber += String.valueOf(a);
} else if (a != ' ' && spaces == 1) {
secondNumber += String.valueOf(a);
} else if (a != ' ' && spaces == 2) {
thirdNumber += String.valueOf(a);
} else if (a == ' ') {
spaces++;
}
}
}
System.out.println(firstNumber + secondNumber + thirdNumber);
}
}
谢谢。
最佳答案
你可以使用:
String[] sizes = {"90 60 90", "90 70 60"};
List<Integer[]> list = Stream.of(sizes).map(
string -> Arrays.asList(string.split("\\s+")).stream()
.map(s -> Integer.parseInt(s))
.toArray(Integer[]::new)
).collect(toList());
显示结果:
list.forEach(array -> System.out.println(Arrays.asList(array)));
输出
[90, 60, 90]
[90, 70, 60]
关于Java 字符串碎片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041746/