其他分享
首页 > 其他分享> > Delphi 字符串替换 SysUtils.StringReplace

Delphi 字符串替换 SysUtils.StringReplace

作者:互联网

Delphi 字符串替换 SysUtils.StringReplace

StringReplace  返回一个字符串,其中一个子字符串替换为另一个子字符串。

原型:

function StringReplace(const S, OldPattern, NewPattern: string;
  Flags: TReplaceFlags): string;
var
  SearchStr, Patt, NewStr: string;
  Offset: Integer;
begin
  if rfIgnoreCase in Flags then
  begin
    SearchStr := AnsiUpperCase(S);
    Patt := AnsiUpperCase(OldPattern);
  end else
  begin
    SearchStr := S;
    Patt := OldPattern;
  end;
  NewStr := S;
  Result := '';
  while SearchStr <> '' do
  begin
    Offset := AnsiPos(Patt, SearchStr);
    if Offset = 0 then
    begin
      Result := Result + NewStr;
      Break;
    end;
    Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern;
    NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt);
    if not (rfReplaceAll in Flags) then
    begin
      Result := Result + NewStr;
      Break;
    end;
    SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt);
  end;
end;

描述:

附.TReplaceFlags 类型(TReplaceFlags指示如何执行搜索和替换操作)

type TReplaceFlags = set of (rfReplaceAll, rfIgnoreCase);

参数:

示例:

var
    sStr: String;
begin
    sStr:= 'Hi TaoRoy 2022 ';
    ShowMessage(StringReplace (sStr, 'o', 'i', []));//Hi TaiRoy 2022  替换第一个

    sStr:= 'Hi TaoRoy 2022 ';
    ShowMessage(StringReplace (sStr, 'o', 'i', [rfReplaceAll]));  //Hi TaiRiy 2022  替换所有
    
    sStr:= 'Hi TaoRoy 2022 Open the world ';
    ShowMessage(StringReplace (sStr, 'o', 'i', [rfReplaceAll])); //Hi TaiRiy 2022 Open the wirld  //替换所有,区分大小写
    
    sStr:= 'Hi TaoRoy 2022 Open the world ';
    ShowMessage(StringReplace (sStr, 'o', 'i', [rfReplaceAll, rfIgnoreCase]));//Hi TaiRiy 2022 ipen the wirld  //替换所有,不区分大小写

  

 

 

 

创建时间:2022.02.17  更新时间:

标签:sStr,Delphi,SysUtils,StringReplace,Hi,字符串,OldPattern,替换
来源: https://www.cnblogs.com/guorongtao/p/15904496.html