Home > Software engineering >  How to generate random characters in dart?
How to generate random characters in dart?

Time:01-25

I want Mack function to generate random characters in range Function will take Enum parameters and return random characters I made this code in the photo but I can't mack it return random characters how this function generate char between 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)

I try t mack this program returns character but I can't

CodePudding user response:

You can generate strings of random characters like this:

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));
}

Example output:

nlsusxijosypogdemickcpteyydbkdlpozipwsmsrdpdmkhwfejfbrsjbkmbrrlyzboazubrefarazxr

For characterSet just choose the set of characters of which you'd like the random string to be composed.

CodePudding user response:

To generate a character string from a number, use String.fromCharCode.

So, to generate a character with ASCII code in the range 65..90 (U 0041..U 005A, A-Z), you can do:

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