从 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
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
技巧是以相反的顺序运行循环:
这样,删除项目的行为只会更改列表中后面元素的索引,并且这些元素已经被处理。
The trick is to run the loop in reverse order:
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.
Andreas 和 David 提供的解决方案假设 ListBox 和 StringList 中的字符串顺序完全相同。这是一个很好的假设,因为您没有另外指出,但如果情况不正确,您可以使用 StringList 的
IndexOf
方法来查找字符串的索引(如果 StringList 已排序,请使用而是查找
)。像这样的东西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, useFind
instead). Something like反过来做(添加而不是删除)怎么样?
How about doing it the other way round (adding instead of deleting)?