string 在 Scala 中有效地重复一个字符/字符串 n 次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31637100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Efficiently repeat a character/string n times in Scala
提问by TimY
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
回答by Travis Brown
For strings you can just write "abc" * 3
, which works via StringOps
and uses a StringBuffer
behind the scenes.
对于字符串,您可以只编写"abc" * 3
,它通过StringOps
并StringBuffer
在幕后使用 a 。
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.
对于角色,我认为您的解决方案非常合理,尽管char.toString * n
可以说更清晰。您是否有任何理由怀疑该List.fill
版本的效率不足以满足您的需求?您可以编写自己的方法来使用 a StringBuffer
(类似于*
on StringOps
),但我建议首先以清晰为目标,然后仅在您有具体证据表明这是您的程序中存在问题时才担心效率。