方法1:推荐方便。
System.Hash 单元
Memo1.Lines.Add(THash.GetRandomString(50));
方法二(自己写的):
function TStrApi.SuiJiString(const AWeiShu: Integer): string; const SourceStr: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var MyRep: string; I: Integer; begin Randomize; for I := 1 to AWeiShu do begin //这里只所以必须加1,是因为SourceStr是从1开始的,而Random是从0开始的,SourceStr[0]就会报错,SourceStr[63]也会报错 MyRep := MyRep + SourceStr[Random(61)+1]; end; Exit(MyRep); end;
PK结果,效率差不多。:
procedure TForm6.Button1Click(Sender: TObject); var I: Integer; startTime: Cardinal; strResult: string; begin startTime := GetTickCount; for I := 1 to 10000 do begin strResult := THash.GetRandomString(50); end; Label1.Caption := '耗时: ' + (GetTickCount - startTime).ToString; end; procedure TForm6.Button2Click(Sender: TObject); const SourceStr: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var strResult: string; I,K: Integer; startTime: Cardinal; begin startTime := GetTickCount; for I := 1 to 10000 do begin Randomize; strResult := ''; for K := 1 to 50 do begin //这里只所以必须加1,是因为SourceStr是从1开始的,而Random是从0开始的,SourceStr[0]就会报错,SourceStr[63]也会报错 strResult := strResult + SourceStr[Random(61)+1]; end; end; Label1.Caption := '耗时: ' + (GetTickCount - startTime).ToString; end;