Delphi搜索字符串在流中的位置


本文整理自网络,侵删。

 (*// 
标题:搜索字符串在流中的位置 
说明:适用于文件搜索等 
设计:Zswang 
支持:wjhu111@21cn.com 
日期:2004-03-21 
//*) 

(*//============================================================================ 
设计思路: 
从流中将数据取到缓冲中 
再逐一对缓冲进行搜索 
============================================================================//*) 

function ScanStream(mStream: TStream; mStr: string): Integer; 
const 
  cBufferSize = $8000; 
var 
  S: string; 
  T: string; 
  I: Integer; 
  L: Integer; 
begin 
  Result := -1; 
  if not Assigned(mStream) then Exit; 
  if mStr = '' then Exit; 
  L := Length(mStr); 
  mStream.Position := 0; 
  SetLength(S, cBufferSize); 
  T := ''; 
  for I := 1 to mStream.Size div cBufferSize do begin 
    mStream.Read(S[1], cBufferSize); 
    Result := Pos(mStr, T + S) - 1; //保留上次搜索的尾部字符~~ 
    T := Copy(S, cBufferSize - L, MaxInt); 
    if Result >= 0 then begin 
      Result := Result + Pred(I) * cBufferSize - Length(T); 
      Exit; 
    end; 
  end; 
  I := mStream.Size mod cBufferSize; 
  SetLength(S, I); 
  if I > 0 then begin 
    mStream.Read(S[1], I); 
    Result := Pos(mStr, T + S) - 1; 
    if Result >= 0 then begin 
      Result := Result + mStream.Size - I - Length(T); 
      Exit; 
    end; 
  end; 
end; { ScanStream } 

//Example 
procedure TForm1.Button1Click(Sender: TObject); 
var 
  vFileStream: TFileStream; 
begin 
  vFileStream := TFileStream.Create('C:\temp\temp.exe', fmShareDenyNone); 
  try 
    Label1.Caption := IntToStr(ScanStream(vFileStream, Edit1.Text)); 
  finally 
    vFileStream.Free; 
  end; 
end;

相关阅读 >>

Delphi基于prewitte算子的图像边缘检测

Delphi和金山词霸制作批量单词翻译

Delphi回调函数高级应用

Delphi 如何从文本内容中删除指定行

Delphi 替换系统文件实现绕过杀软启动

Delphi 数组竟然可以这样定义

Delphi 获得控件所在的窗体

Delphi setpriorityclass 设置当前程序的优先级

Delphi gmt时间与tdatetime转换

Delphi d10.x 安卓app开发中按返回键后程序不退出程序的方法

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...