2014-04-08 175 views

回答

17

要回答你的第一个问题,没有内置的函数。手动循环很容易。这应做到:

for I := mylist.count - 1 downto 0 do 
begin 
    if Trim(mylist[I]) = '' then 
    mylist.Delete(I); 
end; 

注意,for循环必须经过反向列表,从数-1降至0这个工作开始。

使用Trim()是可选的,具体取决于是否要删除仅包含空白的字符串。更改if语句if mylist[I] = '' then只会移除完全是空的字符串。

这里是表示动作的代码一个完整的程序:

procedure TMyForm.Button1Click(Sender: TObject); 
var 
    I: Integer; 
    mylist: TStringList; 
begin 
    mylist := TStringList.Create; 
    try 
    // Add some random stuff to the string list 
    for I := 0 to 100 do 
     mylist.Add(StringOfChar('y', Random(10))); 
    // Clear out the items that are empty 
    for I := mylist.count - 1 downto 0 do 
    begin 
     if Trim(mylist[I]) = '' then 
     mylist.Delete(I); 
    end; 
    // Show the remaining items with numbers in a list box 
    for I := 0 to mylist.count - 1 do 
     ListBox1.Items.Add(IntToStr(I)+' '+mylist[I]); 
    finally 
    mylist.Free; 
    end; 
end; 
+2

反向遍历是至关重要的(+1)。也许答案应该更好地说一下这个词,而不是告诉关于“可选”的“修剪”部分的细节。 – Wolf

-1

这消除了修剪和删除任何的TStringList兼容的对象incur..should工作开销的另一种方式。

S := Memo1.Lines.Text; 

// trim the trailing whitespace 
While S[Length(S)] In [#10, #13] Do 
    System.Delete(S, Length(S), 1); 

// then do the rest 
For I := Length(S) DownTo 1 Do 
    If (S[I] = #13) And (S[I-1] = #10) Then 
    System.Delete(S, I, 2); 
+0

您的解决方案为了解**而引入了大量**开销。但在标准化过程之后,它错过了将文本应用于“Memo1.Lines.Text”。顺便说一句,这与'TStrings'不仅'TStringList'兼容,试着检查'Memo1.Lines.Text'的类型。 – Wolf