以前用数组来生成随机字符串,工作效率太低了!今天无意间发现了个函数,效果还不错。
function GetRandStr(len : Integer; lowercase : Boolean = True; num : Boolean = True; uppercase : Boolean = true) : string; const upperStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; lowerStr = 'abcdefghijklmnopqrstuvwxyz'; numStr = '0123456789'; var sourceStr : string; i : Integer; begin sourceStr := ''; Result := ''; if uppercase = True then sourceStr := sourceStr + upperStr; if lowercase = True then sourceStr := sourceStr + lowerStr; if num = True then sourceStr := sourceStr + numStr; if (sourceStr = '') or (len<1) then exit; Randomize; for i:=1 to len do begin Result := Result + sourceStr[Random(Length(sourceStr)-1)+1]; end; end;
调用方法:
GetRandStr(20);//20为字符串长度
标签:delphi
发表评论