2010. május 4., kedd

How to search and replace strings in a TMemo


How to search and replace strings in a TMemo


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:

procedure TForm1.Button2Click(Sender: TObject);
  i: integer;
  s1: string;
  SearchStr: string;
  NewStr: string;
  place: integer;
  SearchStr := 'line';
  NewStr := 'OneEye';
  for i := 0 to Memo1.Lines.Count - 1 do
    s1 := Memo1.Lines[i];
      Place := pos(SearchStr, s1);
      if place > 0 then
        Delete(s1, Place, Length(SearchStr));
        Insert(NewStr, s1, Place);
        Memo1.Lines[i] := s1;
      place = 0;

Nincsenek megjegyzések:

Megjegyzés küldése