Generate three random characters in Delphi

Your code is converting integer index values to strings. Note that your only reference to your constants is to take their length. You return indices rather than characters.

You could fix your code by using the integer indices you generate to reference elements within your string constants. Mason and Ken showed how to do that.

Personally I would do away with the constants and write

Chr(ord('a') + Random(26))

and

Chr(ord('A') + Random(26))

and

Chr(ord('0') + Random(10))

The ordinal values of these characters were designed way back when to allow such code.


You're adding the result of Random to your finalr, not the random letter from the constants.

Try something like this instead - it uses the return of Random as the index into the string constant characters:

function generate(cantidad: integer): string;
const
  letras_mi = 'abcdefghijklmnopqrstuvwxyz';
  letras_ma = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  numeros = '0123456789';
begin
  Result := '';
  Result := Result + letras_mi[Random(Length(letras_mi)) + 1];
  Result := Result + letras_ma[Random(Length(letras_ma)) + 1];
  Result := Result + numeros[Random(Length(numeros)) + 1];
end;

Tags:

Delphi