By Alvin Alexander. Last updated: February 21, 2021
As a brief note today, here’s a Scala method to generate a random string that is random length and also contains blank spaces:
def genRandomVariableLengthStringWithBlankSpaces(r: scala.util.Random): String = {
val ab = ArrayBuffer[Char]()
val maxLength = r.nextInt(100) + 50 //range of 50-149
for (i <- 1 to maxLength) {
if (i % 5 == 0)
ab.append(' ')
else
ab.append(r.nextPrintableChar)
}
val charSeq: mutable.Seq[Char] = Random.shuffle(ab)
charSeq.mkString + "\n"
}
I created this because the methods in the Scala Random
class don’t work for what I need today, which is a string with a lot of blank spaces in it. I’m sure the code can be improved but I’m on a tight deadline today and this is what I came up with in the time allotted.