Generate random word-like string in Delphi

In addition to generating a string with random characters, it is also possible to generate a word-like string that you can use in word game or for authentication keys.

To implement this feature in Delphi (and also FPC/Lazarus), you will create a function with two parameters :

  • The length of the resulted string (integer).
  • A boolean parameter for if the resulted word will start with a vowel letter or a consonants.

The function implementation consist of :

  • Declaring two string constants (one contains all the vowels and the other contains all the consonants), they will be used as characters sets for the random picking.
  • Declaring a boolean variable to alternate picking between vowels and consonants. The initial value is gotten from our boolean parameter (for starting with a vowel).
  • 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 check if the boolean variable is true :
    • Then get a random number from the length of the vowels set, and pick from the vowels set a character which the index is that random number, and add it to the result string.
    • Else, get a random number from the length of the consonants set, and pick from the consonants set a character which the index is that random number, and add it to the result string.
  • The last action inside the loop is to inverse the value of boolean variable.

Here is the final function :

function GenerateRandomWord(const Len: Integer = 16; StartWithVowel: Boolean = False): string;
const
sVowels: string= 'AEIOUY';
sConson: string= 'BCDFGHJKLMNPQRSTVWXZ';

var
i: Integer;
B: Boolean;

begin
B := StartWithVowel;
SetLength(Result, Len);
Randomize;

for i := Low(Result) to High(Result) do
   begin
   if B
      then Result[i] := sVowels[Random(Length(sVowels)) + 1]
      else Result[i] := sConson[Random(Length(sConson)) + 1];
   B := not B;
   end;
end;

Calling this function is just like this, for example :

GenerateRandomWord(6; True);

And you will get a string like “AKOBIN”, with 6 letters and starting with a vowel (as our parameters).

See also

Leave a Reply