How do you generate a random string like this?

$ perl -le '@char=("a".."z","A".."Z");$random = join "",map { $char[int rand(scalar @char)] } 0..15;print $random'
hGAHnriMJzMdnNqZ

the string was built by letters only (including either lowercase or uppercase).
what’s the easy way in scala?

You can use scala.util.Random to generate random characters, e.g. using nextPrintableChar. Combine it with an iterator, to generate a sequence of them and filter to further restrict which characters you want:

Iterator.continually(Random.nextPrintableChar)  //generate random characters
  .filter(_.isLetter)  // restrict to letters only
  .take(15)  // take only the required amount
  .mkString  // combine into string
1 Like
scala> Iterator.continually(Random.nextPrintableChar()).filter(_.isLetter).take(16).mkString
val res20: String = RisBIniiUGLbHvLI

This is really good. thanks a lot.

To generate a string who contains letters only:

Iterator.continually(Random.nextPrintableChar()).filter(_.isLetter).take(16).mkString
val res28: String = HYtlLYtPHruCXARJ

To generate the string who contains numbers only:

Iterator.continually(Random.nextPrintableChar()).filter(_.isDigit).take(16).mkString
val res30: String = 8209883032775117

To generate the string who contains letters or numbers:

Iterator.continually(Random.nextPrintableChar()).filter(_.isLetterOrDigit).take(16).mkString
val res36: String = qh7TMucfNJvnfR1b

To generate the string who contains anything:

Iterator.continually(Random.nextPrintableChar()).take(16).mkString
val res37: String = VQ:|bi[69pv9x#n)

Thanks @crater2150

I have found another similar way:

scala> Random.alphanumeric.filter(_.isLetter).take(16).mkString
val res58: String = HFoGWtNxkCkydkMF
2 Likes

Ah, nice, I didn’t know about that one. If there is already a method for generating any length of characters that’s even better :slight_smile:

2 Likes