如何在 Kotlin 中有效地创建具有特定长度和相同值的字符串

Mas*_*Man 3 kotlin

我知道这可以通过 for 循环来实现,但我正在寻找更好的解决方案。

createDummyString(1,'A') = 'A'
createDummyString(2.'A') = 'AA'
Run Code Online (Sandbox Code Playgroud)

这将用于刽子手。谢谢你。

leo*_*mer 9

你可以像下面的例子那样做。要了解有关字符串的更多信息,请阅读:https : //kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html

fun createDummyString(repeat : Int, alpha : Char) = alpha.toString().repeat(repeat)
Run Code Online (Sandbox Code Playgroud)

附录:

如果你想让它更加 kotlinesque,你也可以定义repeat为扩展函数Char

fun Char.repeat(count: Int): String = this.toString().repeat(count)
Run Code Online (Sandbox Code Playgroud)

并这样称呼它:

'A'.repeat(1)
Run Code Online (Sandbox Code Playgroud)

  • 对于任何只需要创建一个具有定义长度而不使用函数等的字符串的人,您可以使用: (`"A".repeat(20)`) 生成: AAAAAAAAAAAAAAAAAAAA (2认同)

Jit*_*a A 6

CharSequence 有一个用于此目的的扩展方法。

    fun CharSequence.repeat(n: Int): String // for any whole number
Run Code Online (Sandbox Code Playgroud)

例子

    println("A".repeat(4))  // AAAA 
    println("A".repeat(0))  // nothing 
    println("A".repeat(-1)) // Exception
Run Code Online (Sandbox Code Playgroud)

参考: https: //kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/repeat.html

我为此使用中缀运算符创建了一个实用函数:

infix fun Int.times(s : CharSequence): CharSequence{
    return s.repeat(this)
}
//Use like val twoAs = 2 times "A"
println(a) // AA
Run Code Online (Sandbox Code Playgroud)