在Delphi中生成三个随机字符 [英] Generate three random characters in Delphi

查看:201
本文介绍了在Delphi中生成三个随机字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Delphi中的函数生成三个随机字符,代码是这样的:

  function generate cantidad:integer):string; 
const
letras_mi ='abcdefghijklmnopqrstuvwxyz';
const
letras_ma ='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const
numeros ='0123456789';
var
finalr:string;
begin

finalr:='';

finalr:= finalr + IntToStr(Random(Length(letras_mi))+ 1);
finalr:= finalr + IntToStr(Random(Length(letras_ma))+ 1);
finalr:= finalr + IntToStr(Random(Length(numeros))+ 1);

结果:= finalr;

end;

问题是像20142这样的事情,当我实际上等待3个字符时,常量随机变量。

解决方案

您的代码将整数索引值转换为字符串。请注意,您对常量的唯一参考是取长度。你返回索引而不是字符。



您可以使用生成的整数索引来修正代码,以引用字符串常量中的元素。梅森和肯展示了如何做到这一点。



个人我会消除常量,并写

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

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

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

  b $ b  

这些字符的序数值被设计回来允许这样的代码。


Hi I am trying to generate three random characters using a function in Delphi, the code is this:

function generate(cantidad: integer): string;
const
  letras_mi = 'abcdefghijklmnopqrstuvwxyz';
const
  letras_ma = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const
  numeros = '0123456789';
var
  finalr: string;
begin

  finalr := '';

  finalr := finalr + IntToStr(Random(Length(letras_mi)) + 1);
  finalr := finalr + IntToStr(Random(Length(letras_ma)) + 1);
  finalr := finalr + IntToStr(Random(Length(numeros)) + 1);

  Result := finalr;

end;

the problem is that things like 20142 me back when I'm actually waiting 3 characters constant random variables.

解决方案

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.

这篇关于在Delphi中生成三个随机字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆