- - * - WhiteUnicorn - * - -




* #WhiteUnicorn/ StartPage/ Documentation/DelphiFAQ >


3170:Search and replace in strings: a task made easy

KEYWORDS: Search, replace, locate, insert, pos, delete AREA: Application Inter

Search and replace in strings: a task made easy.

An often overlooked, yet strong feature of Delphi is its
history.  This product has it roots, and shares some code
with Turbo Pascal version 1 released in 1983. Since
then, every version of Turbo Pascal added new features,
standard functions and procedures to the language.
Under its current incarnation, Delphi continues to add
features and syntax.

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);
var
  i : integer;
  s1 : string;
  SearchStr : string;
  NewStr : string;
  place : integer;
begin
  SearchStr := 'line';
  NewStr := 'OneEye';
  for i := 0 to Memo1.Lines.Count -1 do begin
    s1 := Memo1.Lines[i];
    Repeat
      Place := pos(SearchStr, s1);
      if place > 0 then begin
        Delete(s1, Place, Length(SearchStr));
        Insert(NewStr, s1, Place);
        Memo1.Lines[i] := s1;
      end; //if-then
    until place = 0;
  end; //for-loop
end;

        TI



* #WhiteUnicorn/ StartPage/ Documentation/DelphiFAQ >



- - * - Anastasija aka WhiteUnicorn - * - - LJLiveJournal
PFPhotoFile