獲取隨機字符串的方法 GetRandomString


方法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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM