2

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

Amin Memariani
  • 726
  • 2
  • 12
  • 33
  • 4
    I'm afraid it's not possible, unless long is actually small enough to fit in Int. String just can't contain so many characters: https://stackoverflow.com/a/1179996/2956272 –  Jul 29 '19 at 20:16
  • @dyukha, wow! never thought about that! – Amin Memariani Jul 29 '19 at 20:18

1 Answers1

1

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(this@repeat.repeat(Integer.MAX_VALUE))
        }
        append(this@repeat.repeat(remainder))
    }
}
Francesc
  • 18,686
  • 4
  • 42
  • 70