9

Is there any build-in function in Delphi to remove all strings from a TStringList which are empty?

How to loop through the list to remove these items?

kobik
  • 21,001
  • 4
  • 61
  • 121
Franz
  • 1,883
  • 26
  • 47

2 Answers2

22

To answer your first question, there is no built in function for that. Looping manually is easy. This should do it:

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

Note that the for loop must traverse the list in reverse starting from Count-1 down to 0 for this to work.

The use of Trim() is optional, depending on whether you want to remove strings that contain just whitespace or not. Changing the if statement to if mylist[I] = '' then will remove only completely empty strings.

Here is a full routine showing the code in action:

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;
dummzeuch
  • 10,975
  • 4
  • 51
  • 158
Graymatter
  • 6,529
  • 2
  • 30
  • 50
  • 2
    The reverse traversal is crucial (+1). Maybe the answer should better say a word about this instead of telling details about an "optional" `Trim` part. – Wolf Nov 10 '16 at 12:42
-1

Another way that eliminates the overhead that Trim and Delete incur..should work with any TStringList compatible object.

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);
camenoj
  • 11
  • 2
  • Your solution introduces a lot of **overhead for understanding** it. But it misses to apply the text to `Memo1.Lines.Text` after the normalization process. BTW this is compatible with `TStrings` not only `TStringList`, try to check the type of `Memo1.Lines.Text`. – Wolf Nov 10 '16 at 12:58