Masked Man
Masked Man

Reputation: 552

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

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.

Upvotes: 8

Views: 8581

Answers (2)

Jitendra A
Jitendra A

Reputation: 1658

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

Upvotes: 6

leonardkraemer
leonardkraemer

Reputation: 6793

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)

Upvotes: 17

Related Questions