1

だから、私は文字列の配列を受け取っています。各要素を分割して新しい配列に保存したいと思います。それに関する多くの問題に直面し、本当に悪い解決策を思いつきました:

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++;
}

ご覧のとおり、2 つの要素を保存するために if ステートメントを作成する必要があります。これが悪いアプローチであることはわかっていますが、これだけで済みました :(

4

3 に答える 3

2

入力配列のインデックスから結果配列のインデックスを計算できます。

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);

(ただし、これは両方の文字列をトリムします)

于 2016-05-25T08:04:03.640 に答える
0
@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);
}
于 2016-05-25T08:04:22.503 に答える