简体   繁体   中英

How to search an array of bytes for "StringA"?

Using FreePascal (or Delphi if no FP examples), given a 2048 byte buffer that is as an "array of bytes", how can I search the buffer for "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"? 
...

Thankyou

I think this will work in fpc without extra Unicode/AnsiString conversion:

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;

Here's the naïve approach whereby we simply walk through the buffer byte by byte looking for the desired string.

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;

I don't use FPC but I expect that this will work unchanged and if not then I'm sure you can convert it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM