2012-04-04 66 views
3

如果使用FreePascal(或Delphi,如果没有FP示例),给定一个2048字节的缓冲区作为“字节数组”,如何在缓冲区中搜索“StringA”?如何搜索“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"? 
... 

三江源

回答

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; 
+0

+1宁可在我看来 – 2012-04-04 21:14:15

+0

谢谢再次LURD。这很有效,很容易理解!它确实有效。我唯一的问题(也是另一个问题)是,返回的偏移量值当然是每个缓冲区段的值,并且与原始源文件中找到的位置无关。因此,如果第一次碰撞位于源文件和第一次读取的缓冲区内,则匹配源文件的偏移量。但在此之后,它与缓冲区相关,并且与原始源文件偏移量不相似。我会考虑这一点。再次感谢! – 2012-04-04 21:29:40

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,但我期望这将工作不变,如果不是,那么我相信你可以转换它。

+1

FPC还具有一个字节的搜索,体系结构无关的原始称为“indexbyte”。这可以用来搜索第一个字节,然后才可以执行comparemem。它是通用实现的基础。 POS() – 2012-04-06 09:23:01