gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:34:09 25 4
gpt4 key购买 nike

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

createDummyString(1,'A') = 'A'
createDummyString(2.'A') = 'AA'

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

最佳答案

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

fun createDummyString(repeat : Int, alpha : Char) = alpha.toString().repeat(repeat)

附录:

如果你想让它更kotlinesque,你也可以定义 repeat作为 Char 上的扩展函数
fun Char.repeat(count: Int): String = this.toString().repeat(count)

并这样称呼它:
'A'.repeat(1)

关于kotlin - 如何在 Kotlin 中有效地创建具有特定长度和相同值的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com