How to create String with certain length and same value effectively in Kotlin

Viewed 3264

I knew this can be achieved with for loop but I am looking for better solution.

createDummyString(1,'A') = 'A'
createDummyString(2.'A') = 'AA'

This will be used in hangman. Thank you.

2 Answers

You can do it like in the example below. To learn more about Strings read this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html

fun createDummyString(repeat : Int, alpha : Char) = alpha.toString().repeat(repeat)

Addendum:

If you want to make it more kotlinesque, you can also define repeat as extension function on Char

fun Char.repeat(count: Int): String = this.toString().repeat(count)

and call it like this:

'A'.repeat(1)

CharSequence has an extension method for this.

    fun CharSequence.repeat(n: Int): String // for any whole number

Example

    println("A".repeat(4))  // AAAA 
    println("A".repeat(0))  // nothing 
    println("A".repeat(-1)) // Exception

Reference : https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/repeat.html

I created a utility function using infix operator for this :

infix fun Int.times(s : CharSequence): CharSequence{
    return s.repeat(this)
}
//Use like val twoAs = 2 times "A"
println(a) // AA
Related