2012-02-09 79 views
2

我試圖拆分StringList的內容分成多個部分(在Delphi)...
聽起來很簡單,但我愣神堵塞:○如何在Delphi中將一個StringList分成兩個字符串列表?

例如,包含StringList的1001線,我想將內容分割成2個StringLists。所以,一個將有500行,另一個將有501行。
無論第一個有501還是第二個500,反之亦然。

如果有人能把我推上正確的道路......
在此先感謝!

天語

回答

5

你可以做這樣的事情:

for I := SL1.Count - 1 downto (SL1.Count div 2) do 
begin 
    SL2.Insert(0, SL1[I]); 
    SL1.Delete(I); 
end; 
+0

+1。我首先寫了這個,但是它要求每次插入時都要將所有放入第二個字符串列表的字符串移動。我改變了我不要求通過使用兩個單獨的循環。根據原始字符串列表的大小,它們大概是相同的性能 - 在更大的列表中,我認爲我的速度稍快,因爲它不必每次重新分配和移動,而只是分配。 :) – 2012-02-09 13:49:08

+0

非常感謝!我會盡快試一試:) – Beny 2012-02-09 14:00:07

+0

完美!現在我會嘗試分成三部分。 – Beny 2012-02-09 14:30:29

3

你可以做手工很輕鬆地:

var 
    i: Integer; 
    MidIndex, HighIndex: Integer; 
begin 
    MidIndex := SLOne.Count div 2; // Center of first list's items 
    HighIndex := SLOne.Count - 1; // End of first list 

    // Copy from center to end of first list, keeping order 
    // of items intact 
    for i := MidIndex to HighIndex do 
    SLTwo.Append(SLOne[i]); 

    // Go back and remove the ones you just put into the second 
    // list. Go backward to prevent going past the end. 
    for i := HighIndex downto MidIndex do 
    SLOne.Delete(i); 
end; 
+0

謝謝你的幫助:) – Beny 2012-02-09 14:02:13

+0

+1這是O(N)而不是Kobik的O(N^2)。一個小問題。是代碼將更易於閱讀與循環邊界的一些解釋性局部變量。而且這也會使兩個迴路覆蓋的範圍更加清晰。 – 2012-02-09 16:28:40

+1

@大衛,好點。這將使它更清楚。完成。 – 2012-02-09 16:33:12

相關問題