Mega Code Archive

 
Categories / Delphi / String
 

How to replace occurences of a substring in a string

Title: How to replace occurences of a substring in a string procedure TForm1.Button1Click(Sender: TObject); var sNewText: string; begin // Replace the first Word "FOX" with "tiger". sNewText := StringReplace('The quick brown fox jumps over the lazy fox.', 'FOX', 'tiger', [rfIgnoreCase]); ShowMessage(sNewText); // Remove all Spaces in a string. sNewText := StringReplace('This is a Text with Spaces', ' ', '', [rfReplaceAll]); ShowMessage(sNewText); // Replace all "True" in a Memo with "False". Memo1.Text := StringReplace(Memo1.Text, 'True', 'False', [rfReplaceAll, rfIgnoreCase]]); end; {2.} { StringReplace is not available for D3/D2/D1 users. Use the slightly modified StringReplace below. (from sysutils.pas but without ANSI support) } type TReplaceFlags = set of (rfReplaceAll, rfIgnoreCase); 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 := UpperCase(S); Patt := UpperCase(OldPattern); end else begin SearchStr := S; Patt := OldPattern; end; NewStr := S; Result := ''; while SearchStr '' do begin Offset := Pos(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; {3.} Replace all OldSubStr in S with NewSubStr. } function ReplaceStr(s, OldSubStr, NewSubStr: string): string; var i: integer; OldSubLen, TotalLength: integer; begin Result := ''; if s '' then begin OldSubLen := Length(OldSubStr); // f¨¹r die Performance - for performance TotalLength := Length(s); i := 1; while i = TotalLength do begin if (i = TotalLength - OldSubLen) and (Copy(s, i, OldSubLen) = OldSubStr) then begin Result := Result + NewSubStr; Inc(i, OldSubLen); end else begin Result := Result + s[i]; Inc(i); end; end; end; end;