How to search an array of bytes for “StringA”?

一笑奈何 提交于 2019-12-07 13:48:13

问题


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


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/10018739/how-to-search-an-array-of-bytes-for-stringa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!