開發過程中常需在資料流(TStream)中搜尋特定字串,該字串可能包含 ASCII 擴展字元或混合編碼。網路上常見的演算法或程式碼冗長、效率不佳,因此自行實作了一個精簡且高效的函數供參考。
function ScanStream(T: TStream; S: String): Integer;
var
i, j: Integer;
p: PChar;
begin
Result := -1; { 預設未找到 }
if (T.Size = 0) or (S = '') then Exit;
GetMem(p, T.Size); { 配置記憶體緩衝區 }
try
T.ReadBuffer(p^, T.Size); { 一次性讀取整個資料流 }
for i := 0 to T.Size - 1 do
begin
{ 嘗試從位置 i 開始比對字串 S }
for j := 1 to Length(S) do
begin
{ 邊界檢查:避免超出緩衝區 }
if (i + j - 1) >= T.Size then Break;
if p[i + j - 1] <> S[j] then Break; { 字元不符,提早結束內層迴圈 }
end;
if j > Length(S) then
begin
Result := i; { 找到,回傳 0-based 位移 }
Break; { 結束外層迴圈 }
end;
end;
finally
FreeMem(p); { 釋放緩衝區 }
end;
end;
ReadBuffer 將整個資料流載入記憶體,避免重複 I/O,適合中小型資料流。Break,減少不必要比較。try...finally 確保緩衝區釋放,並檢查邊界防止存取違規。var
fs: TFileStream;
pos: Integer;
begin
fs := TFileStream.Create('data.bin', fmOpenRead or fmShareDenyWrite);
try
pos := ScanStream(fs, '目標字串');
if pos >= 0 then
ShowMessage(Format('找到於位移 %d', [pos]))
else
ShowMessage('未找到');
finally
fs.Free;
end;
end;
此函數時間複雜度為 O(n×m)(n 為資料流長度,m 為搜尋字串長度),對於較短模式字串(如關鍵字、標記)效能極佳。若需處理超大檔案或高頻搜尋,建議改用 KMP、Boyer-Moore 等進階演算法,或採用記憶體對映檔案(TMemoryMappedFile)避免完整載入。
PChar 改為 PWideChar 並調整步進邏輯。Seek 還原。