我要写一个搜索一段文本内的某一个字符出现的次数和第一次与最后一次出现的地址 该怎么写,请教大家
这是程序显示处的界面当输入一个字符串时,可以显示该字符串一共出现的次数
要在LABEL1和LABEL16上分别显示一个字符串在MEMO1内首次是第几次出现和第一次出现的地址
LABEL18和LABEL20分别显示最后一次出现是第几次和最后一次出来的地址谢谢~
这是程序显示处的界面当输入一个字符串时,可以显示该字符串一共出现的次数
要在LABEL1和LABEL16上分别显示一个字符串在MEMO1内首次是第几次出现和第一次出现的地址
LABEL18和LABEL20分别显示最后一次出现是第几次和最后一次出来的地址谢谢~
function TCalcular.GetCharNum(c:char;s:string):integer;
var
i:integer;
begin
result:=0;
for i:=1 to length(s) do
if s[i]=c then
result:=result+1;
end;//返回字符c从右第n次出现的位置,如果n大于出现的次数将返回-1,如果没找到将返回0
function TCalcular.RightNPos(s:string;c:char;n:integer):integer;
var
i,p:integer;
begin
result:=0;
p:=0;
if n>getcharnum(c,s) then begin result:=-1;exit; end;
for i:=length(s) downto 1 do
begin
if s[i]=c then
BEGIN
p:=p+1;
//showmessage(inttostr(p));
if p=n then
begin
result:=I;
break;
end;
END;
end;
end;
暂认为求位于第几个字节:
//定义记录
type
TSearchRcd = record
SearchStr:string;//需查找的字符串
OccuCount:integer;//一共找到几个
OccuPosition:array of integer;//逐个地址
end;
var
Form1: TForm1;
SearchRcd:TSearchRcd;
implementation{$R *.dfm}procedure TForm1.Btn_SearchClick(Sender: TObject);
var
SearchStr,TempStr:string;
SearchStrLen,MemoTextLen,NewStrStart,NewPosition:integer;
begin
SearchStr:=EditStr.Text;//Edit3
SearchStrLen:=Length(SearchStr);
if SearchStrLen=0 then
begin
showmessage('Please enter string!');
Exit;
end;
SearchRcd.SearchStr:=SearchStr;
SearchRcd.OccuCount:=0;
MemoTextLen:=Memo1.GetTextLen;
NewStrStart:=1;
NewPosition:=pos(SearchStr,Memo1.Text);
While NewPosition<>0 do
begin
with SearchRcd do
begin
inc(OccuCount);
setlength(OccuPosition,OccuCount);
OccuPosition[OccuCount-1]:= NewStrStart+NewPosition-1;
NewStrStart:= OccuPosition[OccuCount-1]+SearchStrLen;
end;
if NewStrStart>MemoTextLen then
break;
TempStr:=copy(Memo1.Text,NewStrStart,MemoTextLen-NewStrStart+1);
NewPosition:=pos(SearchStr,TempStr);
end;
if SearchRcd.OccuCount>0 then
begin
Label_FO.Caption:='1';//Label14
Label_FP.Caption:='No. '+inttostr(SearchRcd.OccuPosition[0])+' byte';//Label18
Label_LO.Caption:=inttostr(SearchRcd.OccuCount);//Label20
Label_LP.Caption:='No. '+inttostr(SearchRcd.OccuPosition[SearchRcd.OccuCount-1])+' byte';//Label22
end
else
begin
Label_FO.Caption:='0';
Label_FP.Caption:='No Found';
Label_LO.Caption:='0';
Label_LP.Caption:='No Found';
Showmessage('No Found!');
end;
end;procedure TForm1.Btn_DisplayClick(Sender: TObject);
var
IndexNum:integer;
begin
IndexNum:=strtointdef(EditNum.Text,0);//Edit2
if EditStr.Text='' then
begin
showmessage('Please enter string!');
Exit;
end;
if EditStr.Text<>SearchRcd.SearchStr then
Btn_Search.Click;
if (IndexNum<1) or (IndexNum>SearchRcd.OccuCount) then
begin
showmessage('Please enter a positive integer no exceed');
Exit;
end;
//选中
Memo1.SetFocus;
Memo1.SelStart:=SearchRcd.OccuPosition[IndexNum-1]-1;
Memo1.SelLength:=Length(SearchRcd.SearchStr);
end;procedure TForm1.Btn_ExitClick(Sender: TObject);
begin
close;
end;如果想找第几行第几列,那就逐行找TempStr:=copy(Memo1.Lines.Strings[i],NewStrStart,MemoTextLen-NewStrStart+1);
OccuPosition分别记录所在的行和列