从 TStringList 中删除字符串

发布于 2024-11-25 22:08:17 字数 271 浏览 3 评论 0原文

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

怎么办?

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

I have a List Box or a List View with items. And I have a String List with the same items (strings) as the List Box/List View. I want to delete all selected items in the List Box/List View from the String List.

How to do?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

许仙没带伞 2024-12-02 22:08:17
for i := ListBox.Count - 1 downto 0 do
  if ListBox.Selected[i] then
    StringList1.Delete(i);
for i := ListBox.Count - 1 downto 0 do
  if ListBox.Selected[i] then
    StringList1.Delete(i);
一杆小烟枪 2024-12-02 22:08:17

技巧是以相反的顺序运行循环:

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

这样,删除项目的行为只会更改列表中后面元素的索引,并且这些元素已经被处理。

The trick is to run the loop in reverse order:

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

This way, the act of deleting an item only changes the indices of elements later in the list, and those elements have already been processed.

帅哥哥的热头脑 2024-12-02 22:08:17

Andreas 和 David 提供的解决方案假设 ListBox 和 StringList 中的字符串顺序完全相同。这是一个很好的假设,因为您没有另外指出,但如果情况不正确,您可以使用 StringList 的 IndexOf 方法来查找字符串的索引(如果 StringList 已排序,请使用 而是查找)。像这样的东西

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;

Solution provided by Andreas and David assumes that the strings are exactly in same order in both ListBox and StringList. This is good assumption as you don't indicate otherwise, but in case it is not true you can use StringList's IndexOf method to find the index of the string (if the StringList is sorted, use Find instead). Something like

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;
弱骨蛰伏 2024-12-02 22:08:17

反过来做(添加而不是删除)怎么样?

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

How about doing it the other way round (adding instead of deleting)?

StringList1.Clear;
for i:=0 to ListBox.Count-1 do
  if not ListBox.Selected[i] then StringList1.Add(ListBox.Items(i));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文