Delphi 6:如何快速在动态数组中搜索子字符串?

Delphi 6: How to search a dynamic array for sub-string quickly?

如何在Delphi 6中搜索char的动态数组以获取子字符串,并获取匹配项的索引,而不是指针?我已经看到了Delphi 6中的函数,这些函数针对字符串执行此操作,但不针对动态char数组执行此操作。有一个名为SearchBuf的函数,但是当我需要的是匹配的数组索引时,该函数将PChar指针返回到匹配位置。

谢谢。


如果您有一个指向比赛的指针,只需减去指向第一个字符的指针,便会得到索引。

1
2
3
4
5
6
7
8
9
var
  Buf, Result: PChar;
  Index: Integer;

Result := SearchBuf(Buf, ...);
if Assigned(Result) then
  Index := Result - Buf
else
  Index := -1; // not found

我非常确定Delphi 6中允许使用指针算术。如果不允许,则首先将指针类型转换为整数类型:

1
Index := Cardinal(Result) - Cardinal(Buf);