代码集中营

delphi搜索字符串在流中的位置
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 }
procedure TForm1.Button1Click(Sender: TObject);
var
vFileStream: TFileStream;
begin
vFileStream := TFileStream.Create('Data.sah', fmShareDenyNone);
try
Label1.Caption := IntToStr(ScanStream(vFileStream, Edit1.Text));
finally
vFileStream.Free;
end;
end;


你可能感兴趣的:(代码集中营)