Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to generate a random alphanumeric string in Kotlin

Tags:

kotlin

I can generate a random sequence of numbers in a certain range like the following:

fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) +  start fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> {   (0..len-1).map {     (low..high).random()   }.toList() } 

Then I'll have to extend List with:

fun List<Char>.random() = this[Random().nextInt(this.size)] 

Then I can do:

fun generateRandomString(len: Int = 15): String{   val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet()       .union(CharArray(9) { it -> (it + 48).toChar() }.toSet())   return (0..len-1).map {       alphanumerics.toList().random()   }.joinToString("") } 

But maybe there's a better way?

like image 434
breezymri Avatar asked Oct 26 '17 00:10

breezymri


People also ask

How do you generate random alphanumeric Strings?

Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.

How do you generate random Strings?

A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters. All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer.


2 Answers

Since Kotlin 1.3 you can do this:

fun getRandomString(length: Int) : String {     val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')     return (1..length)         .map { allowedChars.random() }         .joinToString("") } 
like image 145
WhiteAngel Avatar answered Sep 19 '22 17:09

WhiteAngel


Lazy folks would just do

java.util.UUID.randomUUID().toString() 

You can not restrict the character range here, but I guess it's fine in many situations anyway.

like image 37
Holger Brandl Avatar answered Sep 17 '22 17:09

Holger Brandl