Board index » delphi » Finding a substring

Finding a substring

Does anybody know how to search for a substring in memo field.

thanks,
Vinay Gidwaney

 

Re:Finding a substring


Quote
Vinay Gidwaney wrote:

> Does anybody know how to search for a substring in memo field.

> thanks,
> Vinay Gidwaney

Sure.  Unfourunatly there isn't a meathod (like findsubstr) but you can
find substrings in a memo with a simple procedure.  here is an example
that will work.  (This is if you want to actually hilght the text in the
memo:

procedure TForm1.MemoFind(SubStr:String);
var
  I, J, PosReturn, SkipChars: Integer;
begin
  For I := 0 to Memo1.Lines.Count do
  begin
    PosReturn := Pos(SubStr,Memo1.Lines[I]);
    if PosReturn <> 0 then {found!}
      begin
        Skipchars := 0;
        for J := 0 to I - 1 do
          Skipchars := Skipchars + Length(Memo1.Lines[J]);

        SkipChars := SkipChars + (I*2);
        SkipChars := SkipChars + PosReturn - 1;
        Memo1.SetFocus;
        Memo1.SelStart := SkipChars;
        Memo1.SelLength := Length(SubStr);
      end;
  end;
end;

I took this example from a delphi (2.0) help file and modified it to be
independant of a TFindDialog component.  This will work.  You could also
add a paramater to accept a TMemo component and place this in a generic
code module.

This will only find the first occurance, it would be easy to pass the
starting (position) and only find things after that.  simple if (ex.  if
cPos>sPos then)

                                                                                Michael Grunder
                                                                                micha...@pantheoninc.com

Re:Finding a substring


You could use something like the following:

procedure TForm1.Button3Click(Sender: TObject);
var
   TheRow, TheCol : Integer;
begin
   for TheRow := 0 to Memo1.Lines.Count do
   begin
      TheCol := Pos('TheWord', Memo1.Lines[TheRow]);
      if TheCol > 0 then
         Memo1.Lines.Add(Format('Row = %d, Col = %d',
                                     [TheRow, TheCol]));
   end;

end;

John.

Other Threads