Re: Delphi random string
Posted by webmaster Guido on May 21, 2003 at 18:57:45:
In Reply to: Random string posted by Joey on May 19, 2003 at 19:23:56:
: I was wondering if there is any way of making a random string with Delphi (for use as validation code).
: I would like it to be in letters and number like:
: I would like to be a 6 digit if possible and im not bothered if on the odd occassion its just all number or letters...
: Could any one do this for me?
: I Would like to be in a label... If its not to much hassle ;)
Here's some Delphi code that produces a random string with a length of 6 characters:
procedure TForm1.Button1Click(Sender: TObject); const Chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ!?/*+-'; var S: string; i, N: integer; begin Randomize; S := ''; for i := 1 to 6 do begin N := Random(Length(Chars)) + 1; S := S + Chars[N]; end; Label1.Caption := S; end;
In constant "Chars" you specify which characters may appear in the string. For example, if you want to use all upper- and all lowercase letters, but no other characters, you modify the code like this:
const Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
[ DelphiLand: free Delphi source code, tips, tutorials ]