Generate a random alphanumeric string in Kotlin
This article explores different ways to generate a random alphanumeric string in Kotlin.
The idea is to randomly choose characters from a selected range of characters and construct a string of the desired length.
To construct a random alphanumeric string, the ASCII range should consist of digits, uppercase, and lowercase characters, as shown below. We can easily extend the solution to include any other ASCII characters that fall within the defined range.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun getRandomString(length: Int) : String { val charset = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz0123456789" return (1..length) .map { charset.random() } .joinToString("") } fun main() { val length = 10 val randomString = getRandomString(length) println(randomString) // wlNs0VX8be } |
The code can be shortened with Kotlin ranges:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun getRandomString(length: Int) : String { val charset = ('a'..'z') + ('A'..'Z') + ('0'..'9') return (1..length) .map { charset.random() } .joinToString("") } fun main() { val length = 10 val randomString = getRandomString(length) println(randomString) // SamSU712JQ } |
You can also use the List constructor, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun getRandomString(length: Int) : String { val charset = ('a'..'z') + ('A'..'Z') + ('0'..'9') return List(length) { charset.random() } .joinToString("") } fun main() { val length = 10 val randomString = getRandomString(length) println(randomString) // 1xHFDcMjkJ } |
That’s all about generating a random alphanumeric string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)