有什么函数能够返回字符串中指定字符的个数呢?该如何解决
有什么函数能够返回字符串中指定字符的个数呢?
如题
------解决方案--------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
function GetCharCount( subStr:string;str:string ):Integer;
var
Index:Integer;
tempStr:string;
Count:Integer;
begin
tempStr:= 'aabbccaattff ';
Count:=0;
Index:=Pos( 'a ', tempStr );
while Index > 0 do
begin
Inc( Count );
tempStr:=Copy( tempStr,Index+1,length( tempStr ) - Index );
Index:=Pos( 'a ', tempStr );
end;
Result:=Count;
end;
begin
showmessage( IntToStr( GetCharCount( 'a ', 'aabbccaattff ') ) );
end;
------解决方案--------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
function GetCharCount( subStr:string;str:string ):Integer;
var
Index:Integer;
tempStr:string;
Count:Integer;
begin
tempStr:= 'aabbccaattff ';
Count:=0;
Index:=Pos( 'a ', tempStr );
while Index > 0 do
begin
Inc( Count );
tempStr:=Copy( tempStr,Index+1,length( tempStr ) - Index );
Index:=Pos( 'a ', tempStr );
end;
Result:=Count;
end;
begin
showmessage( IntToStr( GetCharCount( 'a ', 'aabbccaattff ') ) );
end;
------解决方案--------------------------------------------------------
function GetStrCount(vSource,vKey:String):Integer;
var
vTmpSource:TStrings;
vTmpString:String;
begin
vTmpSource:=TStringList.Create;
vTmpString:=vSource; //做个备份
vTmpSource.Text:=StringReplace(vTmpString,vKey,#13#10,[rfReplaceAll, rfIgnoreCase]);
//这里是关键,把关键字改成回车放到TStrings里,TSTrings的个数就是关键字的个数.
Result:=vTmpSource.Count;
end;
------解决方案--------------------------------------------------------
用下面的GetSubStringNumber函数:
function GetSubStringNumber(sString, sSub: String): Integer;
begin
Result := (Length(sString) - Length(StringReplace(sString, sSub, ' ', [rfReplaceAll]))) div Length(sSub);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(GetSubStringNumber( 'abc1abcde2abcdefg3 ', 'abc ')));
end;
评论