PDA

View Full Version : Replace() Function



xGTx
01-08-2005, 06:08 AM
I made this function tonight and thought it'd be usefull to share. Not that it's hard to code, but just something to share (and get feedback on how to make faster ;))

This function is to find and replace all instances of a substring in a string.

function Replace(FindStr, ReplaceWith, Source : String) : String;
var i,c : integer;
begin
c := Length(FindStr);
i := Pos(FindStr, Source);
while i <> 0 do
begin
Source := Copy(Source, 1, i - 1) + ReplaceWith + Copy(Source, i + c, Length(Source));
i := Pos(FindStr, Source);
end;
Result := Source;
end;

Sly
01-08-2005, 07:37 AM
It seems kind of odd to rewrite a function that is already in the RTL, unless it is specifically being written to be faster than the RTL version. StringReplace has already been rewritten to be a lot faster as part of the FastCode project.
http://dennishomepage.gugs-cats.dk/AnsiStrReplaceChallenge.htm

xGTx
01-08-2005, 08:16 PM
... I had no idea there was a function already... :DOH: