Generating a string with random characters is a good feature that can be used for making authentication codes, hash salts, etc.
For using this feature in Delphi (and also FPC/Lazarus), you can create a function with two parameters :
- The length of the resulted string (integer).
- The set of characters (as a string) used to build the resulted string, with a default value (all characters) which is ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890’.
The function implementation consist of :
- Getting the length of the characters set : stored in a variable to be used as a range for the “Random()” function (this function will result an integer from the range).
- Setting our length parameter as a length of the result string.
- Call the “Randomize” procedure to initialize the random number generator with a random value, it is called only once before the loop of number generating.
- Now, a loop (from the first to the last character of the result) to get a random number from the length of our characters set, and pick from the set a character which the index is that random number, and add it to the result string.
Here is the final function :
function GenerateRandomString(const ALength: Integer; const ACharSequence: String = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'): String;
var
Ch, SequenceLength: Integer;
begin
SequenceLength := Length(ACharSequence);
SetLength(Result, ALength);
Randomize;
for Ch := Low(Result) to High(Result) do
Result[Ch] := ACharSequence.Chars[Random(SequenceLength)];
end;
Calling this function is just like this, for example :
GenerateRandomString(6; 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
And you will get a string like “M7DX9H”, with 6 characters consisting of caps letters and numbers (as our parameters).