-1

Hello i am writing some values to a stringlist. And would like to delete a value from the string list.

Currently I write to the string list like this.

   FGamePlay.Locations.strings[0] := ('NumberOfLocations='+inttostr(NOL+1));   //add one to total
   FGameplay.Locations.Add(inttostr(Position.x)+inttostr(Position.Y)+'=pos');  //add the location to list

This will return me a list like so

INDEX    VALUE
[0]       NumberOfLocations=4
[1]       23=pos
[2]       34=pos
[3]       24=pos
[4]       52=pos

Now i try to delete it like this

FGamePlay.Locations.Delete(FGamePlay.Locations.IndexOf(inttostr(ePosition.x)+inttostr(ePosition.Y)));

were ePosition.x + ePosition.Y will equal 23, 34,24,or 52. Thus it should delete the that line but instead when i add this delete line i get index out of bounds -1. I did stop the code just before this line and looked at Locations() and it had all these numbers in there. Also looked at epostion and the X,Y values were 34, thus correct too. Any idea? thanks Glen

4

3 回答 3

6

当您使用该IndexOf函数时,您必须传递确切的字符串来查找,在这种情况下,因为您是以这种方式添加字符串

FGameplay.Locations.Add(inttostr(Position.x)+inttostr(Position.Y)+'=pos'); 

您必须将 添加=pos到要搜索的字符串中,例如

LIndex:=FGamePlay.Locations.IndexOf(inttostr(ePosition.x)+inttostr(ePosition.Y)+'=pos');
If LIndex>=0 then
 FGamePlay.Locations.Delete(LIndex);
于 2012-07-04T20:56:24.803 回答
1

正如 RRUZ 所说,您要删除的字符串缺少“=pos”后缀。

为了更有效地调试它,您应该更多地分解代码。如果您有此等效代码:

str := inttostr(ePosition.x)+inttostr(ePosition.Y);
pos := FGamePlay.Locations.IndexOf(str);
FGamePlay.Locations.Delete(pos);

你会在线路上得到一个错误pos :=,这将允许更容易地查看错误的来源。

您还可以考虑制作如下函数:

function MakePosString(Position : Point);
begin
   Result := inttostr(ePosition.x)+inttostr(ePosition.Y)+'=pos';
end;

然后您可以调用该函数而不是重新实现该代码,并保证您的字符串是一致的。

于 2012-07-04T20:56:40.213 回答
1

虽然我同意其他人所说的关于考虑为手头的工作使用更好的数据结构的说法,但我认为为了将来遇到类似问题的任何人,值得一提的是其他人尚未发现的东西。

你的表情:

IntToStr(ePosition.x) + IntToStr(ePosition.y)

当被视为名称/值列表时,标识字符串列表中条目的名称。也就是说,一个 TStringList,其中每个项目的形式为“name=value”。虽然修复代码的一种方法是附加字符串的其余部分('=pos'),但这当然仅在每个命名值的“值”部分始终为“pos”时才有效。

如果给定命名值的“pos”值可能不同或未知,那么您仍然可以通过仅使用名称部分查找项目的索引来找到它:

  itemName  := IntToStr(ePosition.x) + IntToStr(ePosition.y);
  itemIndex := fGamePlay.Locations.IndexOfName(itemName);
  if itemIndex > -1 then
    fGamePlay.Locations.Delete(IndexOfName(itemName));
于 2012-07-05T03:34:31.663 回答