Board index » delphi » Q: Fast replacing short strings in a long string

Q: Fast replacing short strings in a long string

I am looking for a fast procedure which would able to replace all the
occurences of a certain string (for example 'Microsoft') to another
(e.g. 'Micro$oft') in quite a large (a few hundred kB's) string.
I know, how to do this using Pos, Delete and Insert, but how to do it
faster using PChar handling routines? It's probably the fastest way, but
at this stage I have a little knowledge of PChars, pointers and stuff
like that.

Michal Jaskolski
================
Please, help the victims of the largest flood in Poland ever!
More information: http://wp.cnt.pl/Powodz/index.eng.html  

 

Re:Q: Fast replacing short strings in a long string


: j...@gdansk.sprint.pl (Michal Jaskolski) wrote:

Quote
>I am looking for a fast procedure which would able to replace all the
>occurences of a certain string (for example 'Microsoft') to another
>(e.g. 'Micro$oft') in quite a large (a few hundred kB's) string.
>I know, how to do this using Pos, Delete and Insert, but how to do it
>faster using PChar handling routines? It's probably the fastest way, but
>at this stage I have a little knowledge of PChars, pointers and stuff
>like that.

This is SLOW but does not consume too much memory:

- Find the first occurrence using StrPos ("start")
- adjust the size of string to be replaced
  (move all the other data up or down)
- write the replacement **byte by byte** to the PChar
  found by StrPos, do NOT use StrCopy (this would
  mess up your original string):

   for i := 1 to StrLen(replacement) do
   begin
     start[0] := replacement[i];
     inc(start);
   end;
- loop with StrPos until start = nil;

Another approach which consumes much more memory is to
selectively copy the data into a newly allocated string, discard
of the old string and finally return the new string.
--
Stefan.Hoffmeis...@Uni-Passau.de
http://kakadu.rz.uni-passau.de/~w4hoff01/

Other Threads