Search code examples
stringkotlinrandomcharreturn

Kotlin - How to get 5(or selected numbers) random Char from charRange '0..'z'


Did you know to get 5(or selected Number) random char from a Range '0..'z' ?? In "fun putCharTogehter" must call with specific numbers and must put these Char to new String with + Operator and then return to "fun main" with complete strong that is have size 5 or selected

In concept i know how to do but yeah only in concept.

Wish output Example: 38dj(

fun main() {

    println(putCharTogehter(5))


}


fun putCharTogehter(stringSize: Int): String {
    var charRange = ('0'..'z').random()
    return charRange.toString()

}




Solution

  • You can do this by first creating array of chars and then converting it to a string:

    fun putCharTogehter(stringSize: Int): String {
        return CharArray(stringSize) {
            ('0'..'z').random()
        }.concatToString()
    }