当n较长时,如何在Kotlin中重复字符串n次

当n较长时,如何在Kotlin中重复字符串n次,kotlin,Kotlin,我知道使用函数可以将一个字符串重复n次,但是如果n大于一个Int的大小,你可以这样做,尽管这样长的字符串很可能会耗尽内存 fun String.repeat(times: Long): String { val inner = (times / Integer.MAX_VALUE).toInt() val remainder = (times % Integer.MAX_VALUE).toInt() return buildString { repeat(

我知道使用函数可以将一个字符串重复n次,但是如果n大于一个
Int
的大小,你可以这样做,尽管这样长的字符串很可能会耗尽内存

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))
    }
}

恐怕这是不可能的,除非long实际上足够小,可以容纳Int。字符串不能包含这么多字符:@dyukha,哇!从没想过!这实际上是行不通的(除非
times
适合
Int
或字符串为空),dyukha的评论是正确的。@AlexeyRomanov,除了
字符串
,还有其他数据类型可以保存该数量的值吗?@Aminemariani不在标准库中,除非我遗漏了什么。您甚至不能定义自己的实现
CharSequence
,它也有
int
长度。