Delphi 內建 StringReplace(SysUtils 單元)功能強大,但若需自行實作簡易版本以理解原理或避免引入額外單元,可參考下列邏輯:尋找子字串位置 → 刪除 → 插入新字串。
function ReplaceSubStr(const S, Source, Target: string): string;
var
PosFound, SrcLen: Integer;
begin
Result := S;
SrcLen := Length(Source);
if SrcLen = 0 then Exit; // 避免無限迴圈
PosFound := Pos(Source, Result);
while PosFound > 0 do
begin
Delete(Result, PosFound, SrcLen);
Insert(Target, Result, PosFound);
// 繼續尋找下一個(從插入位置之後開始)
PosFound := Pos(Source, Result, PosFound + Length(Target));
end;
end;
while 迴圈支援全域取代。Pos 的第三個參數(起始搜尋位置)避免重複掃描已處理部分。SrcLen = 0 守衛,防止 Source 為空字串導致無限迴圈。var
Str: string;
begin
Str := 'Hello World, Hello Delphi';
Str := ReplaceSubStr(Str, 'Hello', 'Hi');
// 結果:'Hi World, Hi Delphi'
ShowMessage(Str);
end;