【发布时间】:2019-03-02 18:40:01
【问题描述】:
我正在尝试实现一个从给定字符串中提取由 $ 字符分隔的“占位符”的函数。
处理字符串:
val stringToParse = "ignore/me/$aaa$/once-again/ignore/me/$bbb$/still-to-be/ignored
结果应该是:
Seq("aaa", "bbb")
以下使用var 切换累积的实现的Scala 惯用替代方案是什么?
import fiddle.Fiddle, Fiddle.println
import scalajs.js
import scala.collection.mutable.ListBuffer
@js.annotation.JSExportTopLevel("ScalaFiddle")
object ScalaFiddle {
// $FiddleStart
val stringToParse = "ignore/me/$aaa$/once-again/ignore/me/$bbb$/still-to-be/ignored"
class StringAccumulator {
val accumulator: ListBuffer[String] = new ListBuffer[String]
val sb: StringBuilder = new StringBuilder("")
var open:Boolean = false
def next():Unit = {
if (open) {
accumulator.append(sb.toString)
sb.clear
open = false
} else {
open = true
}
}
def accumulateIfOpen(charToAccumulate: Char):Unit = {
if (open) sb.append(charToAccumulate)
}
def get(): Seq[String] = accumulator.toList
}
def getPlaceHolders(str: String): Seq[String] = {
val sac = new StringAccumulator
str.foreach(chr => {
if (chr == '$') {
sac.next()
} else {
sac.accumulateIfOpen(chr)
}
})
sac.get
}
println(getPlaceHolders(stringToParse))
// $FiddleEnd
}
【问题讨论】:
-
要清楚,在这个例子中,你希望所有字符串都在匹配的 $?您能否发布您目前拥有的代码,以便我们了解您开始的方向?
-
我已经用一个使用 var 的例子更新了这个问题
标签: scala