'Generate Random String/letter in Scala
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
sizeis an Int
The 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
}
Solution 1:[1]
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
Solution 2:[2]
Actually the fastest method to generate Random ASCII String is the following
val rand = new Random()
val Alphanumeric = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes
def mkStr(chars: Array[Byte], length: Int): String = {
val bytes = new Array[Byte](length)
for (i <- 0 until length) bytes(i) = chars(rand.nextInt(chars.length))
new String(bytes, StandardCharsets.US_ASCII)
}
def nextAlphanumeric(length: Int): String = mkStr(Alphanumeric, length)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ruurtjan Pul |
| Solution 2 | Harold |
