Generate Random String/letter in Scala
Solution 1
Found a better solution:
Random.alphanumeric.filter(_.isLetter).head
A better solution as jwvh commented: Random.alphanumeric.dropWhile(_.isDigit)
Solution 2
For better control of the contents, select the alphabet yourself:
val alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
def randStr(n:Int) = (1 to n).map(_ => alpha(Random.nextInt(alpha.length))).mkString
pedrorijo91
MSc in Computer Science from Instituto Superior Técnico, Lisbon. Currently working at Onfido, building the new identity standard for the internet. Former fullstack developer at Tripadvisor. Former product engineer at Feedzai, preventing e-commerce fraud using machine learning and AI. Former software developer at Codacy, an automated code review tool.
Updated on July 25, 2022Comments
-
pedrorijo91 almost 2 years
I'm trying to generate a random String, and these are the possibilities I've found:
Random.nextPrintableChar()
, which prints letters, numbers, punctuationRandom.alphanumeric.take(size).mkString
, which prints letters and numbersRandom.nextString(1)
, which prints Chinese chars almost every time lol
Random is scala.util.Random
size
is an IntThe second option almost does the job, but I need to start with a letter. I found
Random.nextPrintableChar()
but it also prints punctuation.What's the solution?
My solution so far was:
val low = 65 // A val high = 90 // Z ((Random.nextInt(high - low) + low).toChar
Inspired by
Random.nextPrintableChar
implementation:def nextPrintableChar(): Char = { val low = 33 val high = 127 (self.nextInt(high - low) + low).toChar }