从TStringList中删除字符串

max*_*fax 6 delphi string tstringlist

我有一个列表框或列表视图与项目.我有一个字符串列表与列表框/列表视图相同的项目(字符串).我想从字符串列表中删除列表框/列表视图中的所有选定项目.

怎么做?

for i:=0 to ListBox.Count-1 do
  if ListBox.Selected[i] then
    StringList1.Delete(i); // I cannot know exactly an index, other strings move up
Run Code Online (Sandbox Code Playgroud)

And*_*and 21

for i := ListBox.Count - 1 downto 0 do
  if ListBox.Selected[i] then
    StringList1.Delete(i);
Run Code Online (Sandbox Code Playgroud)


Dav*_*nan 17

诀窍是以相反的顺序运行循环:

for i := ListBox.Count-1 downto 0 do
  if ListBox.Selected[i] then 
    StringList1.Delete(i);
Run Code Online (Sandbox Code Playgroud)

这样,删除项目的行为仅改变列表中稍后的元素索引,并且这些元素已经被处理.

  • 今天慢吗? (5认同)
  • @maxfax:但是,我的答案要好得多,因为我有很好的品味用空格包围二元减法运算符!(开玩笑!) (4认同)
  • @Andreas实际上,我会说你很喜欢使用`Count-1`而不是'pred(Count)`!! (3认同)
  • @maxfax Andreas几秒前回答.将鼠标悬停在*XX分钟前*的文本上,以查看时间戳.另一方面,我解释了为什么它首先工作!! ;-) (2认同)

ain*_*ain 10

Andreas和David提供的解决方案假定字符串在ListBox和StringList中的顺序完全相同.这是一个很好的假设,因为你没有另外说明,但如果不是这样,你可以使用StringList的IndexOf方法来查找字符串的索引(如果StringList已排序,请Find改为使用).就像是

var x, Idx: Integer;
for x := ListBox.Count - 1 downto 0 do begin
   if ListBox.Selected[x] then begin
      idx := StringList.IndexOf(ListBox.Items[x]);
      if(idx <> -1)then StringList.Delete(idx);
   end;
end;
Run Code Online (Sandbox Code Playgroud)


Fra*_*itt 5

反过来(添加而不是删除)如何做呢?

StringList1.Clear;
for i:=0 to ListBox.Count-1 do
  if not ListBox.Selected[i] then StringList1.Add(ListBox.Items(i));
Run Code Online (Sandbox Code Playgroud)