Comment detail

文字変換表に基く文字列の変換 (Nested Flatten)

基本版+拡張版です。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import scala.collection.mutable.Stack
def tr(pat:String, rep:String, str:String) = {
  def expand(pat:String) = pat.indexOf('-') match {
    case -1 => pat
    case _  =>
      ((new Stack[char], false) /: pat){case ((s,f),c) => (c, f) match {
        case ('-', _)  => (s, true)
        case (c, true) => s.push((s.pop.toInt to c.toInt).map(_.toChar):_*);
                          (s, false)
        case (c, _)    => s.push(c); (s, false)
      }}._1.mkString("")
  }
  val m = Map(expand(pat).toList.zip(expand(rep).toList):_*)
  (new StringBuilder /: str){(b,c) => b.append(m.getOrElse(c,c)) }.toString
}

println(tr("qwertyuiop", "QWERTYUIOP", "typewriter"))
println(tr("a-z", "A-Z", "typewriter"))

Index

Feed

Other

Link

Pathtraq

loading...