Amin Memariani
Amin Memariani

Reputation: 912

How to repeat a string n times in Kotlin, when n is Long

I know using repeat function we can repeat a string n times but what if the n is bigger than a size of an Int

Upvotes: 2

Views: 771

Answers (1)

Francesc
Francesc

Reputation: 29260

You can do this, though you are likely to run out of memory with such long strings

fun String.repeat(times: Long): String {
    val inner = (times / Integer.MAX_VALUE).toInt()
    val remainder = (times % Integer.MAX_VALUE).toInt()
    return buildString {
        repeat(inner) {
            append([email protected](Integer.MAX_VALUE))
        }
        append([email protected](remainder))
    }
}

Upvotes: 1

Related Questions