9

I'm trying to generate a random String, and these are the possibilities I've found:

  1. Random.nextPrintableChar(), which prints letters, numbers, punctuation
  2. Random.alphanumeric.take(size).mkString, which prints letters and numbers
  3. Random.nextString(1), which prints Chinese chars almost every time lol

Random is scala.util.Random

size is 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
  }

3 Answers 3

20

Found a better solution:

Random.alphanumeric.filter(_.isLetter).head

A better solution as jwvh commented: Random.alphanumeric.dropWhile(_.isDigit)

3
  • Or, if all you need is for it to start with a letter: Random.alphanumeric.dropWhile(_.isDigit)
    – jwvh
    Jan 7, 2016 at 22:15
  • even better solution @jwvh :) Jan 7, 2016 at 22:26
  • 10
    And if you need something like a 3 digit number Random.alphanumeric.filter(_.isDigit).take(3).mkString Mar 14, 2017 at 17:56
5

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
6
  • honestly, i don't really like that approach Jan 8, 2016 at 15:51
  • 3
    (1 to n).map(_ => alpha(Random.nextInt(alpha.length))).mkString
    – Mahdi
    Mar 8, 2018 at 10:23
  • 1
    Random.nextInt.abs sometimes returns a negative value, resulting in a java.lang.StringIndexOutOfBoundsException for this snippet. See docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int- for more details. In the .map, use this instead: _ => alpha(Random.nextInt(size)) Jun 12, 2020 at 14:20
  • @RuurtjanPul As per scala doc, it should never return negative value scala-lang.org/api/2.12.6/scala/Int.html#abs:Int
    – Jus12
    Jun 16, 2020 at 7:02
  • Then I'm afraid the docs are incorrect. Try Int.MinValue.abs. Jun 16, 2020 at 11:37
1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.