In this tutorial, you shall learn how to get a random character from given string in Kotlin, using String.random() function, with examples.

Kotlin – Get Random Character from String

To get random character from String in Kotlin, call random() method on this string.

Example

In the following example, we take a string in str, and call random() method on this string to get a character from this string randomly.

Main.kt

fun main(args: Array<String>) {
    var str = "abcd@$#1234"
    var result = str.random()
    println(result)
}

Output

d

We can use this function, to generate a password will allowed characters taken in a string.

In the following example, we generate a password of length 12 using String.random() method.

Main.kt

fun main(args: Array<String>) {
    var str = "abcdefghijklmnopqrstuvwxyzABCD@$#*123456789"
    var password = ""
    for (i in 1..12) {
        password += str.random()
    }
    println(password)
}

Output

9p5Anw4m46Bp
ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned how to get a character randomly from given string using String.random() method, with the help of Kotlin example programs.