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
-
4I'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/2956272user2956272– user29562722019-07-29 20:16:11 +00:00Commented Jul 29, 2019 at 20:16
-
@dyukha, wow! never thought about that!Amin Memariani– Amin Memariani2019-07-29 20:18:14 +00:00Commented Jul 29, 2019 at 20:18
Add a comment
|
1 Answer
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))
}
}
3 Comments
Alexey Romanov
This won't actually work (unless
times fits into Int or the string is empty), dyukha's comment is correct.Amin Memariani
@AlexeyRomanov, Is there any other data type that can hold that amount of value other than
String?Alexey Romanov
@AminMemariani Not in the standard library, unless I miss something. You can't even define your own implementing
CharSequence, that has int length too.