Pacific-Design.com

    
Home Index

1. Scala

2. Random String

Scala / Random String /

Generate Random String

  /**
    * Generate Random String
     * @param length
    * @return
    */
  private def randomAlphaNumericString(length: Int): String = {
    val chars = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')
    randomStringFromCharList(length, chars)
  }

  /**
    * Geenerate Random Characters
    * @param length
    * @param chars
    * @return
    */
  private def randomStringFromCharList(length: Int, chars: Seq[Char]): String = {
    val sb = new StringBuilder
    for (i <- 1 to length) {
      val randomNum = util.Random.nextInt(chars.length)
      sb.append(chars(randomNum))
    }
    sb.toString
  }