Delphi Memo1文本搜索并高亮


本文整理自网络,侵删。

 
unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm2 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

function search(pat: string; text: string): integer;
var
  i, j, k, m, n: integer;
  skip: array [0..MAXCHAR] of integer;
  found: boolean;
begin
  found := FALSE;
  search := 0;
  m := length(pat);
  if m=0 then
  begin
    search := 1;
    found := TRUE;
  end;
  for k:=0 to MAXCHAR do
    skip[k] := m;   {*** Preprocessing ***}
  for k:= m-1 downto 1 do
    skip[ord(pat[k])] := m-k;
  k := m;
  n := length(text);            {*** Search ***}
  while not found and (k <= n) do
  begin
    i := k; j := m;
    while (j >= 1) do
    begin
      if text[i] <> pat[j] then
        j := -1
      else
      begin
        j := j-1;
        i := i-1;
      end;
      if j = 0 then
      begin
        search := i+1;
        found := TRUE;
      end;
      k := k + skip[ord(text[k])];
    end;
  end;
end;


procedure TForm2.Button1Click(Sender: TObject);
var
  FoundIdx: Integer;
begin
  // search() returns 0 if the text isn't found or the index of the
  // start of the string if the text is found
  FoundIdx := search(Edit1.Text, Memo1.Text);
  if FoundIdx > 0 then
  begin
    // Found text: highlight it in memo (TMemo.HideSelection must be
    // false for this to work). Since memo selections are 0 based, we
    // subtract 1 from the found index, which is 1 based.

    Memo1.SelStart := FoundIdx - 1;
    Memo1.SelLength := Length(Edit1.Text);
     Memo1.SetFocus;
  end
  else
    ShowMessage('Text not found');
end;



end.

相关阅读 >>

Delphi opendialog1 添加文件打开多选模式

Delphi 系统服务状态获取管理员用户名

Delphi版插apc杀进程驱动源码

Delphi adoquery的post和updatebatch

Delphi xe6 firemonkey移动应用程序的twebbrowser html页面上运行javascript

Delphi xe使用tjsonobject解析json数据

Delphi让tedit控件的内容居中或右对齐,限制位数,仅允许输入数字

Delphi一句话复制整个文件夹(当然包括嵌套文件夹)

Delphi firedac tfddatamove 导出csv

Delphi读写utf-8、unicode格式文本文件

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...