所以,我收到一个字符串数组,我想拆分每个元素并将其保存到一个新数组中,我遇到了很多问题,并提出了一个非常糟糕的解决方案:
String[] timeSlots = { "13:00:00 - 14:00:00", "15:00:00 - 16:00:00","17:00:00 - 18:00:00" };
String[] t = new String[6];
String temp[] = new String[6];
int j = 1;
for (int i = 0; i < 3; i++) {
temp = timeSlots[i].split("\\-");
if(j == 1){
t[0] = temp[0];
t[1] = temp[1].trim();
}
else if(j == 2){
t[2] = temp[0];
t[3] = temp[1].trim();
}
else{
t[4] = temp[0];
t[5] = temp[1].trim();
}
j++;
}
正如你所看到的,我必须创建一个 if 语句来保存两个元素,我知道这是一个不好的方法,但这就是我所能做到的:(
最佳答案
您可以根据输入数组中的索引计算结果数组中的索引:
String[] t = new String[2*timeSlots.length];
for (int i = 0; i < timeSlots.length; i++) {
String[] temp = timeSlots[i].split("\\-");
t[2*i] = temp[0].trim();
t[2*i+1] = temp[1].trim();
}
或者使用流:
t = Arrays.stream(timeSlots).flatMap(slot -> Arrays.stream(slot.split("\\-")).map(String::trim)).toArray(String[]::new);
(但这会修剪两个字符串)
关于java - String.Split() 用于字符串数组并保存到新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430934/