如果用TRichEdit 更简单:This example requires a TRichEdit, a TButton, and a TFindDialog. Clicking the button click will display a Find Dialog to the right of the edit control. Filling in the "Find what" text and pressing the Find Next button will select the first matching string in the Rich Edit control that follows the previous selection.procedure TForm1.Button1Click(Sender: TObject);begin FindDialog1.Position := Point(RichEdit1.Left + RichEdit1.Width, RichEdit1.Top); FindDialog1.Execute; end;procedure TForm1.FindDialog1Find(Sender: TObject); var FoundAt: LongInt; StartPos, ToEnd: Integer; begin with RichEdit1 do begin { begin the search after the current selection if there is one } { otherwise, begin at the start of the text } if SelLength <> 0 then StartPos := SelStart + SelLength; else StartPos := 0; { ToEnd is the length from StartPos to the end of the text in the rich edit control } ToEnd := Length(Text) - StartPos; FoundAt := FindText(FindDialog1.FindText, StartPos, ToEnd, [stMatchCase]); if FoundAt <> -1 then begin SetFocus; SelStart := FoundAt; SelLength := Length(FindDialog1.FindText); end; end; end;
Copy()函数是返回字符串从指定位置开始的指定个数的字符! 我那里的“D”是返回值!
简单的,pos函数可以得到子串中子字串的首次出现位置。SelStart/SelLength可以用来标示一段文字。Copy可以按位置得到字串的子串。统计关键字的出现次数用简单的循环加上pos函数就可以完成(这个算法效率不是很高,但是很容易懂):function CountKeywords(AString, ASubString: string): cardinal; var p: cardinal; begin Result:=0; p:=pos(ASubString, AString); while p <> 0 do begin Inc(Result); AString:=copy(AString,p+Length(ASubString),MAXINT); p:=pos(ASubString, AString); end; end;共参考。
另外,Edit2.Text为D中的“D”是什么?是目标字符串吗?
谢谢!
Clicking the button click will display a Find Dialog to the right of the edit control. Filling in the "Find what" text and pressing the Find Next button will select the first matching string in the Rich Edit control that follows the previous selection.procedure TForm1.Button1Click(Sender: TObject);begin
FindDialog1.Position := Point(RichEdit1.Left + RichEdit1.Width, RichEdit1.Top);
FindDialog1.Execute;
end;procedure TForm1.FindDialog1Find(Sender: TObject);
var
FoundAt: LongInt;
StartPos, ToEnd: Integer;
begin
with RichEdit1 do
begin
{ begin the search after the current selection if there is one }
{ otherwise, begin at the start of the text }
if SelLength <> 0 then StartPos := SelStart + SelLength;
else StartPos := 0; { ToEnd is the length from StartPos to the end of the text in the rich edit control } ToEnd := Length(Text) - StartPos; FoundAt := FindText(FindDialog1.FindText, StartPos, ToEnd, [stMatchCase]);
if FoundAt <> -1 then
begin
SetFocus;
SelStart := FoundAt;
SelLength := Length(FindDialog1.FindText);
end;
end;
end;
我那里的“D”是返回值!
var
p: cardinal;
begin
Result:=0;
p:=pos(ASubString, AString);
while p <> 0 do
begin
Inc(Result);
AString:=copy(AString,p+Length(ASubString),MAXINT);
p:=pos(ASubString, AString);
end;
end;共参考。