在Scala中有效地重复一个字符/字符串n次 [英] Efficiently repeat a character/string n times in Scala

查看:1803
本文介绍了在Scala中有效地重复一个字符/字符串n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更有效地执行下列操作:

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

$ b b

推荐答案

对于字符串,你可以写abc* 3 http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.StringOps> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆