Author: Jonas Bilinkevicius
How to create a random string
Answer:
Solve 1:
1 var2 LoopInt: Integer;
3 DirName, FullName, RanStr: string;
4 FileSavedTo: TextFile;
5 { Length of string to create }6 RandArray: array[0..4087] of Char;
7 FirstCount: Extended;
8 begin9 FirstCount := GetTickCount;
10 Label2.Caption := '';
11 Randomize;
12 RanStr := '';
13 DirName := Directory95ListBox1.Directory;
14 if DirName[Length(DirName)] <> '\' then15 DirName := DirName + '\';
16 FullName := DirName + Edit1.Text;
17 if FileExists(FullName) then18 DeleteFile(FullName);
19 for LoopInt := Low(RandArray) to High(RandArray) do20 begin21 RanStr := RanStr + Chr(Random(255 - 32 + 1) + 32);
22 end;
23 AssignFile(FileSavedTo, FullName);
24 if FileExists(FullName) then25 Reset(FileSavedTo)
26 else27 Rewrite(FileSavedTo);
28 Writeln(FileSavedTo, RanStr);
29 CloseFile(FileSavedTo);
30 Label2.Caption := ' Done ';
31 Label4.Caption := FloatToStr((GetTickCount - FirstCount) / 1000);
32 FileListBox1.Update;
33 end;
Randomize should be called only once in an application. You should therefore put
the above code into the form's OnCreate event for example, or remove Randomize from
the above code and call it from the form's OnCreate event handler.
Solve 2:
This routine creates passwords from a string table with selected chars. Note: The
password length must be shorter than the given string table length.
34 35 {Call Randomize only once at application start.}36 37 procedure TForm1.FormCreate(Sender: TObject);
38 begin39 Randomize;
40 end;
41 42 function RandomPwd(PWLen: integer): string;
43 {Set the table of chars to be used in passwords}44 const45 StrTable: string = '!#$%&/()=?@<>|{[]}\*~+#;:.-_' + 'ABCDEFGHIJKLMabcdefghijklm' +
46 '0123456789' + 'ÄÖÜäöüß' + 'NOPQRSTUVWXYZnopqrstuvwxyz';
47 var48 N, K, X, Y: integer;
49 begin50 {Check the maximum password length}51 if (PWlen > Length(StrTable)) then52 K := Length(StrTable) - 1
53 else54 K := PWLen;
55 SetLength(result, K); {Set the length of the result string}56 Y := Length(StrTable); {Table length for inner loop}57 N := 0; {Loop start value}58 while N < K do59 begin{Loop to create K chars}60 X := Random(Y) + 1; {Get next random char}61 {Check for the presence of this char in the result string}62 if (pos(StrTable[X], result) = 0) then63 begin64 inc(N); {Not found }65 Result[N] := StrTable[X];
66 end;
67 end;
68 end;
69 70 //Used like this:71 72 procedure TForm1.Button1Click(Sender: TObject);
73 var74 cPwd: string;
75 begin76 {e.g. create a random password string with 30 chars}77 cPwd := RandomPwd(30);
78 { ... }79 end;