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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:25:48  来源:igfitidea点击:

Efficiently repeat a character/string n times in Scala

stringscalacharconcatenationstring-concatenation

提问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 StringOpsand uses a StringBufferbehind the scenes.

对于字符串,您可以只编写"abc" * 3,它通过StringOpsStringBuffer在幕后使用 a 。

For characters I think your solution is pretty reasonable, although char.toString * nis arguably clearer. Do you have any reason to suspect the List.fillversion 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),但我建议首先以清晰为目标,然后仅在您有具体证据表明这是您的程序中存在问题时才担心效率。