在 Scala 中有效地重复一个字符/字符串 n 次 [英] Efficiently repeat a character/string n times in Scala
问题描述
我想更有效地做以下事情:
I would like to do the following more efficiently:
def repeatChar(char:Char, n: Int) = List.fill(n)(char).mkString
def repeatString(char:String, n: Int) = List.fill(n)(char).mkString
repeatChar('a',3) // res0: String = aaa
repeatString("abc",3) // res0: String = abcabcabc
推荐答案
对于字符串,你可以写 "abc" * 3
,它通过 StringOps
并在后面使用 StringBuffer
场景.
For strings you can just write "abc" * 3
, which works via StringOps
and uses a StringBuffer
behind the scenes.
对于字符,我认为您的解决方案非常合理,尽管 char.toString * n
可以说更清晰.您是否有任何理由怀疑 List.fill
版本的效率不足以满足您的需求?您可以编写自己的方法来使用 StringBuffer
(类似于 StringOps
上的 *
),但我建议先明确目标,然后再仅当您有具体证据表明这是您的程序中存在的问题时才担心效率.
For characters I think your solution is pretty reasonable, although char.toString * n
is arguably clearer. Do you have any reason to suspect the List.fill
version isn't efficient enough for your needs? You could write your own method that would use a StringBuffer
(similar to *
on StringOps
), but I would suggest aiming for clarity first and then worrying about efficiency only when you have concrete evidence that that's an issue in your program.
这篇关于在 Scala 中有效地重复一个字符/字符串 n 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!