方法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;
http://www.cnblogs.com/del88/p/6911709.html