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

Time:11-04

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()

}



CodePudding user response:

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()
}

CodePudding user response:

Just another option:

fun putCharTogether(stringSize: Int): String = buildString {
    repeat(stringSize) { 
        append(('0'..'z').random())
    }
}

CodePudding user response:

Another way:

fun putCharTogether(stringSize: Int): String {
    return (1..stringSize).joinToString("") { ('0'..'z').random().toString() }
}

OR

fun putCharTogether(stringSize: Int): String {
    return (1..stringSize).map { ('0'..'z').random() }.joinToString("")
}
  • Related