Mirror

How to create a random string (Views: 714)


Problem/Question/Abstract:

How to create a random string

Answer:

Solve 1:

var
  LoopInt: Integer;
  DirName, FullName, RanStr: string;
  FileSavedTo: TextFile;
  { Length of string to create }
  RandArray: array[0..4087] of Char;
  FirstCount: Extended;
begin
  FirstCount := GetTickCount;
  Label2.Caption := '';
  Randomize;
  RanStr := '';
  DirName := Directory95ListBox1.Directory;
  if DirName[Length(DirName)] <> '\' then
    DirName := DirName + '\';
  FullName := DirName + Edit1.Text;
  if FileExists(FullName) then
    DeleteFile(FullName);
  for LoopInt := Low(RandArray) to High(RandArray) do
  begin
    RanStr := RanStr + Chr(Random(255 - 32 + 1) + 32);
  end;
  AssignFile(FileSavedTo, FullName);
  if FileExists(FullName) then
    Reset(FileSavedTo)
  else
    Rewrite(FileSavedTo);
  Writeln(FileSavedTo, RanStr);
  CloseFile(FileSavedTo);
  Label2.Caption := ' Done ';
  Label4.Caption := FloatToStr((GetTickCount - FirstCount) / 1000);
  FileListBox1.Update;
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.

{Call Randomize only once at application start.}

procedure TForm1.FormCreate(Sender: TObject);
begin
  Randomize;
end;

function RandomPwd(PWLen: integer): string;
{Set the table of chars to be used in passwords}
const
  StrTable: string = '!#$%&/()=?@<>|{[]}\*~+#;:.-_' + 'ABCDEFGHIJKLMabcdefghijklm' +
  '0123456789' + 'ÄÖÜäöüß' + 'NOPQRSTUVWXYZnopqrstuvwxyz';
var
  N, K, X, Y: integer;
begin
  {Check the maximum password length}
  if (PWlen > Length(StrTable)) then
    K := Length(StrTable) - 1
  else
    K := PWLen;
  SetLength(result, K); {Set the length of the result string}
  Y := Length(StrTable); {Table length for inner loop}
  N := 0; {Loop start value}
  while N < K do
  begin {Loop to create K chars}
    X := Random(Y) + 1; {Get next random char}
    {Check for the presence of this char in the result string}
    if (pos(StrTable[X], result) = 0) then
    begin
      inc(N); {Not found }
      Result[N] := StrTable[X];
    end;
  end;
end;

Used like this:

procedure TForm1.Button1Click(Sender: TObject);
var
  cPwd: string;
begin
  {e.g. create a random password string with 30 chars}
  cPwd := RandomPwd(30);
  { ... }
end;

<< Back to main page