在循环TStringList项时,是否存在避免越界索引错误的良好实践?

Bła*_*żej 1 delphi pascal tstringlist

:)

首先,我的代码

procedure TForm1.Button3Click(Sender: TObject);
var tempId,i:integer;
begin
tempId:=strtoint(edit5.Text);
plik:=TStringList.Create;
plik.LoadFromFile('.\klienci\'+linia_klient[id+1]+'.txt');
if (plik.Count=1) then
  begin
  label6.Caption:='then';
    if (tempId=StrToInt(plik[0])) then
      begin
      Label6.Caption:='Zwrócono';
      plik.Delete(0);
    end
  end
else
for i:=0 to plik.Count-2 do
  begin
    if (tempId=StrToInt(plik[i])) then
    begin
      Label6.Caption:='Zwrócono';
      plik.Delete(i);
    end;
  end;
plik.SaveToFile('.\klienci\'+linia_klient[id+1]+'.txt');
plik.Free;
end;
Run Code Online (Sandbox Code Playgroud)
  • for i:=0 to plik.Count-2 do我可以删除任何元素但不能删除.
  • for i:=0 to plik.Count-1 do我可以删除任何元素而不是从头开始.因为否则List索引越界.

怎么样?如何安全搜索和删除TStringList中的元素?

ain*_*ain 8

从列表中删除intems时,你想使用downto循环,即

for i := plik.Count-1 downto 0 do
  begin
    if (tempId=StrToInt(plik[i])) then
    begin
      Label6.Caption:='Zwrócono';
      plik.Delete(i);
    end;
  end;
Run Code Online (Sandbox Code Playgroud)

这样可以确保在删除项目时,循环索引在从列表开头的列表末尾移动时保持有效.


Dav*_*nan 5

这是一个经典问题.一个for循环的循环的开始计算循环边界一次,所以你流掉这也解释了你的索引出界失误结束.

但即使for循环每次评估循环边界就像一个while不会真正有帮助的那样.删除元素时,减少Count1并将其余元素向下移动到列表中的一个元素.因此,您可以更改所有仍处理元素的索引.

标准技巧是循环列表:

for i := List.Count-1 downto 0 do
  if DeleteThisItem(i) then
    List.Delete(i);
Run Code Online (Sandbox Code Playgroud)

以这种方式编写时,调用会Delete影响已经处理的元素的索引.