如何在dart中生成随机字符?

rta7y2nd  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(255)

我想mack函数生成随机字符的范围函数将枚举参数,并返回随机字符我在照片中做了这个代码,但我不能mack它返回随机字符这个函数如何生成字符之间65 - 90 [

import 'dart:convert';
import 'dart:math' ;
final _random = new Random();
enum enCharType {SmallLetter,CapitalLetter, SpecialCharacter, Digit}
int RandomNumber(dynamic min, dynamic max)  => min + _random.nextInt(max - min);

dynamic GetRandomCharacter(enCharType CharType)
{
  switch(CharType)
  {
    case enCharType.SmallLetter:

     return 
  }
}
void main() {

  print(GetRandomCharacter(enCharType.SmallLetter));


}

https://i.stack.imgur.com/0uLs5.png
我试着让这个程序返回字符,但是我不能

ru9i0ody

ru9i0ody1#

要从数字生成字符 string,请使用String.fromCharCode
因此,要生成ASCII码在65..90(U+0041..U+005 A,A-Z)范围内的字符,您可以执行以下操作:

String charInRange(int min, int max) => 
    String.fromCharCode(min + _random.nextInt(max - min));
sg2wtvxw

sg2wtvxw2#

可以生成如下所示的随机字符串:

import 'dart:math' as math;

String generateRandomString(String characterSet, int length) {
  var rng = math.Random();
  var buf = StringBuffer();
  for (var i = 0; i < length; i++) {
    var index = rng.nextInt(characterSet.length);
    buf.write(characterSet.substring(index, index+1));
  }
  return buf.toString();
}

void main() {
  var characterSet = 'abcdefghijklmnopqrstuvwxyz';
  var desiredLength = 80;
  print(generateRandomString(characterSet, desiredLength));
}

输出示例:

nlsusxijosypogdemickcpteyydbkdlpozipwsmsrdpdmkhwfejfbrsjbkmbrrlyzboazubrefarazxr

对于characterSet,只需选择您希望组成随机字符串的字符集。

相关问题