delphi 怎样在memo查找某个字符?

2024-12-27 21:40:56
推荐回答(2个)
回答1:

很简单啊!

procedure TForm1.btnSearchClick(Sender: TObject);
var
SearchText:string;
k:integer;
begin
SearchText:=edit1.Text; //查找edit1中输入的文本
k:=pos(SearchText,memo1.Text); //求出首次出现SearchText的位置
if k=0 then
showmessage('找不到')
else
begin
memo1.SelStart:=k;
memo1.SelLength:=length(SearchText);
memo1.SetFocus; //这一句很重要,否则就会看不到文字被选中
end;
end;

这段代码我不到3分钟就写出来了,而且一点错都没有。

回答2:

完善一下似乎因该

...
memo1.SelStart:=0;
s:=memo.Text ;

k:=pos(SearchText,s);
while k>0 do
begin
memo1.SelStart:=memo1.SelStart+k;
memo1.SelLength:=length(SearchText);
memo1.SetFocus;
//... 等待消息 ...
//继续执行
delete(s,1,k);
k:=pos(SearchText,s) ;
end;

//////////////////////
Var
FoundAt: Integer;
LastFoundAt: Integer;
SearchStrLen: Integer;
AllText: String;
Begin //"查找下一个" 算法
Result := -1;
FoundAt := 0;

If frDown In Options Then //"向下" 查找,找出搜索范围
AllText := System.Copy(Text, SelStart + SelLength + 1, Length(Text))
Else //"向上" 查找,找出搜索范围
AllText := System.Copy(Text, 1, SelStart);

If Not (frMatchCase In Options) Then //非大小写敏感
Begin
AllText := UpperCase(AllText);
SearchStr := UpperCase(SearchStr);
End;

If frDown In Options Then //执行"向下查找"
Begin
FoundAt := Pos(SearchStr, AllText);
If FoundAt = 0 Then
Exit;
//定位光标到指定的字符串
FoundAt := SelStart + SelLength + FoundAt - 1;
End;

If Not (frDown In Options) Then //执行"向上查找"
Begin
SearchStrLen := Length(SearchStr);
FoundAt := Pos(SearchStr, AllText);
If FoundAt = 0 Then //整个部分没找到
Exit
Else //至少找至一个相符的字串
Begin
LastFoundAt := FoundAt; //保存搜到的"第1个字串"位置
Repeat
FoundAt := Posex(SearchStr, AllText, FoundAt + SearchStrLen);
If FoundAt <> 0 Then
LastFoundAt := FoundAt;
Until FoundAt = 0;
FoundAt := LastFoundAt - 1;
End;
End;

Result := FoundAt;

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/gencheng/archive/2007/04/07/1555957.aspx