下面的函数能根据输入的字符串数组,返回各个字符串在数组中的出现次数(次数存放在
TStringList的Objects数组中):
function StrCount(SA:array of String):TStringList;
var
i,idx:Integer;
begin
Result:=TStringList.Create;
Result.Sorted:=true;
for i:=Low(SA) to High(SA) do
begin
idx:=Result.IndexOf(SA);
if idx>=0 then
Result.Objects[idx]:=TObject(Integer(Result.Objects[idx])+1)
else
Result.AddObject(SA,TObject(1));
end;
end;
用法:
procedure TForm1.Button1Click(Sender: TObject);
var
SL:TStringList;
Str:String;
i:Integer;
begin
SL:=StrCount(['111','22','45','22','','875','111','22']);
Str:='';
for i:=0 to SL.Count-1 do
Str:=Str+Format('%s: %d 次'#13#10,[SL,Integer(SL.Objects)]);
SL.Free
//一定要记得Free !
ShowMessage(Str);
end;