从TStringList删除空字符串 [英] Remove empty strings from TStringList
问题描述
Delphi中是否有任何内置函数可以删除 TStringList
中所有为空的字符串?
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?
推荐答案
要回答您的第一个问题,没有内置函数。手动循环很容易。这应该做到这一点:
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;
请注意,为此,for循环必须从Count-1开始向下遍历该列表,直到0
Note that the for loop must traverse the list in reverse starting from Count-1 down to 0 for this to work.
使用 Trim()
是可选的,具体取决于您是否要删除包含以下内容的字符串还是空白。如果mylist [I] =''将 if
语句更改为,则
将仅删除完全为空的字符串。
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;
这篇关于从TStringList删除空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!