Delphi中是否有内置函数可以从TStringList
中删除所有空字符串?
如何循环遍历列表以删除这些项?
回答你的第一个问题,没有内置函数可以实现。手动循环很容易。这应该可以做到:
for I := mylist.count - 1 downto 0 do
begin
if Trim(mylist[I]) = '' then
mylist.Delete(I);
end;
请注意,为了使这个程序正常运行,for循环必须从Count-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;
另一种消除 Trim 和 Delete 开销的方法..应该适用于任何 TStringList 兼容对象。
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);
Memo1.Lines.Text
的步骤。顺便提一下,这与TStrings
不仅兼容,还兼容TStringList
,请尝试检查Memo1.Lines.Text
的类型。 - Wolf
Trim
部分。 - Wolf