String.Split() для массива строк и сохранения в новый массив
Итак, я получаю массив String, и я хотел бы разделить каждый элемент и сохранить его в новый массив, и я столкнулся с множеством проблем с этим и нашел действительно плохое решение:
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 для сохранения двух элементов, я знаю, что это плохой подход, но это все, с чем я смог прийти:(
3 ответа
Решение
Вы можете вычислить индекс в массиве результатов из индекса во входном массиве:
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);
(это обрезает обе строки)
Если структура вашего массива всегда одна и та же, вы можете сначала объединить элементы вашего массива в строку и снова делиться через каждый час. Пример:
public static void main(String a[]){
String[] timeSlots = { "13:00:00 - 14:00:00", "15:00:00 - 16:00:00","17:00:00 - 18:00:00" };
String joined = String.join(" - ", timeSlots);// gives you a string like this "13:00:00 - 14:00:00 - 15:00:00 - 16:00:00 - 17:00:00 - 18:00:00"
String [] newArray = joined.split(" - ");
System.out.println(Arrays.toString(newArray));
}
@Test
public void splitTimeSlotsToArray() {
String[] timeSlots = { "13:00:00 - 14:00:00", "15:00:00 - 16:00:00","17:00:00 - 18:00:00" };
// We already know how many times there are, each range (or slot)
// has two times specified in it. So it's the length of timeSlots times 2.
String[] times = new String[timeSlots.length*2];
for (int i = 0; i < timeSlots.length; i++) {
String timeSlotParts[] = timeSlots[i].split(" - ");
times[i*2] = timeSlotParts[0];
times[i*2 + 1] = timeSlotParts[1];
}
assertEquals(Arrays.asList(
"13:00:00", "14:00:00", "15:00:00", "16:00:00", "17:00:00", "18:00:00"
), Arrays.asList(times));
}
// This is a more preferable option in terms of readability and
// idiomatics in Java, however it also uses Java collections which you
// may not be using in your class
@Test
public void splitTimeSlotsToList() {
String[] timeSlots = { "13:00:00 - 14:00:00", "15:00:00 - 16:00:00","17:00:00 - 18:00:00" };
Collection<String> times = new ArrayList<>();
// Go over each time slot
for (String timeSlot : timeSlots) {
// Go over each time in each time slot
for (String time : timeSlot.split(" - ")) {
// Add that time to the times collection
times.add(time);
}
}
// you can convert the Collection to an array too:
// String[] timesArray = times.toArray(new String[timeStamps.size()]);
assertEquals(Arrays.asList(
"13:00:00", "14:00:00", "15:00:00", "16:00:00", "17:00:00", "18:00:00"
), times);
}