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

2
  • 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: stackoverflow.com/a/1179996/2956272 Commented Jul 29, 2019 at 20:16
  • @dyukha, wow! never thought about that! Commented Jul 29, 2019 at 20:18

1 Answer 1

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([email protected](Integer.MAX_VALUE))
        }
        append([email protected](remainder))
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This won't actually work (unless times fits into Int or the string is empty), dyukha's comment is correct.
@AlexeyRomanov, Is there any other data type that can hold that amount of value other than String?
@AminMemariani Not in the standard library, unless I miss something. You can't even define your own implementing CharSequence, that has int length too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.