使用FreePascal(或Delphi,如果没有FP示例),给定一个2048字节的缓冲区作为“字节数组”,如何在缓冲区中搜索“StringA”?
var
Buffer : array[1..2048] of byte;
...
repeat
i := 0;
BlockRead(SrcFile, Buffer, SizeOf(Buffer), NumRead);
// Now I want to search the buffer for "StringA"?
...
三江源
答案 0 :(得分:6)
我认为这将在fpc中有效,无需额外的Unicode / AnsiString转换:
function Find(const buf : array of byte; const s : AnsiString) : integer;
//returns the 0-based index of the start of the first occurrence of S
//or -1 if there is no occurrence
var
AnsiStr : AnsiString;
begin
SetString(AnsiStr, PAnsiChar(@buf[0]), Length(buf));
Result := Pos(s,AnsiStr) - 1; // fpc has AnsiString overload for Pos()
end;
答案 1 :(得分:4)
这是一种天真的方法,我们只需逐字节遍历缓冲区,寻找所需的字符串。
function Find(const Buffer: array of Byte; const S: AnsiString): Integer;
//returns the 0-based index of the start of the first occurrence of S
//or -1 if there is no occurrence
var
N: Integer;
begin
N := Length(S);
if N>0 then
for Result := low(Buffer) to high(Buffer)-(N-1) do
if CompareMem(@Buffer[Result], Pointer(S), N) then
exit;
Result := -1;
end;
我不使用FPC,但我希望这可以保持不变,如果没有,那么我相信你可以转换它。