Create an alphanumeric string
I need test company names like "rnd_company_blah23haf9", "rnd_company_g356fhg57" etc.
Is it possible to do something like
import scala.util.Random
val company = s"rnd_company_${Random.alphanumeric take 10 ?????}"
if someone can fill in ????? sure.
+3
FelixHJ
source
to share
3 answers
Use .mkString("")
to create String
from Stream
:
scala> val company = s"rnd_company_${Random.alphanumeric take 10 mkString}"
company: String = rnd_company_BbesF0EY1o
+17
Marth
source
to share
You have an example here
scala> val x = Random.alphanumeric
x: scala.collection.immutable.Stream[Char] = Stream(Q, ?)
scala> x take 10 foreach println
Q
n
m
x
S
Q
R
e
P
B
So, you can try this:
import scala.util.Random
val company = s"rnd_company_${(xx take 10).mkString}"
+2
Carlos Vilchez
source
to share
Something more verbose than the answers above, but this one will help you limit the alphabet:
def randomText(textLength: Int = 10, alphabet: List[Char] = ('a' to 'd').toList) = {
(1 to textLength).toList.map { charPos =>
val randomIndex = (Math.random() * alphabet.length).floor.toInt
alphabet(randomIndex)
}.mkString("")
}
0
rogermenezes
source
to share