Removing blank lines from list of strings that is from TStringList which is widely used for an array of strings.
We have reused the IsStringEmpty function from other article called Different String type verification functions in Delphi.
To remove the trailing blank lines from a TStringList, use the below function. This function can be used for TWideStringList too by writing a overloaded version of this function using a TWideStringList as parameter.
procedure TStringListTrimTrailBlankLines(t: TStringList);
begin
while true do
begin
if t.Count = 0 then exit;
if IsStringEmpty(t[t.Count - 1]) = false then exit;
t.Delete(t.Count - 1);
end;
end;
To delete the leading blank lines from a TStringList, use the below function. This function can be used for TWideStringList too by writing a overloaded version of this function using a TWideStringList as parameter.
procedure TStringListTrimLeadBlankLines(t: TStringList);
begin
while true do
begin
if t.Count = 0 then exit;
if IsStringEmpty(t[0]) = false then exit;
t.Delete(0);
end;
end;
To strip of blank lines from whole list of strings, use below function. This function can be used for TWideStringList too by writing a overloaded version of this function using a TWideStringList as parameter.
procedure TStringListStripBlankLines(t: TStringList);
var
i: integer;
begin
for i := t.Count - 1 downto 0 do
if IsStringEmpty(t[i]) then
t.Delete(i);
end;
To delete a specified number of blank lines from a list of strings, use below function. The same can used for TWideStringList by overloading the function.
procedure TStringListStripMultipleBlankLines(t: TStringList; NumberOfLines: integer);
var
idx, count: integer;
begin
idx := 0;
Count := 0;
while (idx = NumberOfLines) then
begin
t.delete(idx);
dec(Count);
end
else
inc(idx);
end
else
begin
Count := 0;
inc(idx);
end;
end;
- 751 reads