Delphi - Find text in large TMemo

Kawaii-Hachii picture Kawaii-Hachii · Jan 5, 2012 · Viewed 18.1k times · Source

I have a TMemo which contains quite a lot of texts, 80M (about 400K lines).

The TMemo is set with WordWrap = FALSE, there is no need to find texts that wrapped in 2 lines.

I need a fast way to find a text, from the beginning, and also find next.

So, I put a TEdit for putting the text to find and a TButton to find the text in the TMemo.

I was thinking to use Pos(), checking line by line, but that will be slow. And I don't know how to determine the TMemo.Lines[index] for current cursor position.

Anyone can come up with solution?

Thanks

UPDATE:

I found a solution from here: Search thru a memo in Delphi?

The SearchText() function works, fast, and very fast. Took couple of seconds to search unique string at the bottom end.

Answer

kludg picture kludg · Jan 5, 2012

A little addition to the previous answers: you can get the line number without selecting the pattern found, like this:

procedure TForm1.Button3Click(Sender: TObject);
var
  I, L: Integer;

begin
  Memo1.WordWrap:= False;
  Memo1.Lines.LoadFromFile('Windows.pas');
  I:= Pos('finalization', Memo1.Text);
  if I > 0 then begin
    L := SendMessage(Memo1.Handle, EM_LINEFROMCHAR, I - 1, 0);
    ShowMessage('Found at line ' + IntToStr(L));
// if you need to select the text found:
    Memo1.SelStart := I - 1;
    Memo1.SelLength := Length('finalization');
    Memo1.SetFocus;
  end;
end;

Note that line number is zero-based, also you should subtract 1 from Pos result to obtain zero-based offset for SendMessage and TMemo.SelStart.