首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 自製字串取代函數:替換指定子字串

     編輯:Delphi

需求場景

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;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved