Author: Lou Adler
Search and replace
Answer:
Almost every text editor / word processor has the ability to search for a given
string and replace it with another. If you're planning on adding similar
functionality to your application, here's an example of where all of it can start:
1 function SearchAndReplace(
2 sSrc, sLookFor, sReplaceWith
3 : string)
4 : string;
5 var
6 nPos, nLenLookFor: integer;
7 begin
8 nPos := Pos(sLookFor, sSrc);
9 nLenLookFor := Length(sLookFor);
10 while (nPos > 0) do
11 begin
12 Delete(sSrc, nPos, nLenLookFor);
13 Insert(sReplaceWith, sSrc, nPos);
14 nPos := Pos(sLookFor, sSrc);
15 end;
16 Result := sSrc;
17 end;
For example, let's say you have a string -- 'this,is,a,test' -- and you want to
replace the commas with spaces. Here's how you'd call SearchAndReplace():
18
19 SearchAndReplace('this,is,a,test', ',', ' ')
20
21 SearchAndReplace() will now return the string 'this is a test'.
|