Author: Jonas Bilinkevicius
How to search and replace strings in a TMemo
Answer:
Doing search and replace on strings has been made trivial because of these 3
functions: Pos(), Delete(), and Insert(). Pos() takes two parameters, a pattern
search string, and a string to find the pattern in - it returns the location of the
string, or 0 if it does not exist. Delete() takes three parameters, the string to
delete from, location of where to start deleting, and how much to delete.
Similarly, Insert() takes three parameters too. The string that will be inserted,
the string to insert into, the location to insert.
Many class properties use strings to store values, so one can use this method on
any of them. For instance, the searching and replacing of an entire TMemo component
might look like this:
1 procedure TForm1.Button2Click(Sender: TObject);
2 var
3 i: integer;
4 s1: string;
5 SearchStr: string;
6 NewStr: string;
7 place: integer;
8 begin
9 SearchStr := 'line';
10 NewStr := 'OneEye';
11 for i := 0 to Memo1.Lines.Count - 1 do
12 begin
13 s1 := Memo1.Lines[i];
14 repeat
15 Place := pos(SearchStr, s1);
16 if place > 0 then
17 begin
18 Delete(s1, Place, Length(SearchStr));
19 Insert(NewStr, s1, Place);
20 Memo1.Lines[i] := s1;
21 end;
22 until
23 place = 0;
24 end;
25 end;
|