Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty strings from TStringList

Tags:

delphi

vcl

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?

like image 355
Franz Avatar asked Apr 08 '14 17:04

Franz


People also ask

How do I remove empty elements from a list?

Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this task. remove() generally removes the first occurrence of an empty string and we keep iterating this process until no empty string is found in list.

How do I remove blank spaces from a list in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


1 Answers

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;
like image 102
Graymatter Avatar answered Oct 15 '22 01:10

Graymatter