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
            Asked
            
        
        
            Active
            
        
            Viewed 611 times
        
    2
            
            
        
        Amin Memariani
        
- 830
- 3
- 17
- 39
- 
                    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: 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 Answers
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
        
- 25,014
- 10
- 66
- 84
- 
                    1This won't actually work (unless `times` fits into `Int` _or_ the string is empty), dyukha's comment is correct. – Alexey Romanov Jul 30 '19 at 07:00
- 
                    @AlexeyRomanov, Is there any other data type that can hold that amount of value other than `String`? – Amin Memariani Jul 30 '19 at 18:09
- 
                    @AminMemariani Not in the standard library, unless I miss something. You can't even define your own implementing `CharSequence`, that has `int` length too. – Alexey Romanov Jul 30 '19 at 18:14