首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

有什么函数能够返回字符串中指定字符的个数呢?该如何解决

2012-04-06 
有什么函数能够返回字符串中指定字符的个数呢?如题[解决办法]procedure TForm1.Button1Click(Sender: TObj

有什么函数能够返回字符串中指定字符的个数呢?
如题

[解决办法]
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;

热点排行