开发者

How to optimize this simple function in scala

I wrote a simple function, to replace all the b char of a string to *, and if it ends with c, then replace the ending c to #.

So I write the code as:

开发者_运维知识库
object Main {
    def fix(text: String) = {
        val s = text.replace("b", "*")
        if (s.endsWith("c")) {
            s.stripSuffix("c") + ("#")
        } else s
    }
    def main(args: Array[String]) {
        println(fix("abbbbccc")) // -> a***cc#
    }
}

I think this code is not very good, not in scala-way. Since I'm new to scala, I don't know how to optimize it into a single line, or just a chain?

For example:

def fix(text: String) = {
    text.replace("b", "*") op { t =>
        if (t.endsWith("c")) {
            t.stripSuffix("c") + ("#")
        } else t
    }
}

This is a chain I expected. Note the method op, I hope there is such a method, like map. That we don't have to define a variale here.

Or there is some other API in scala, can make this method just one line.


It's better to use regular expressions in such cases:

def fix(s: String) = s.replace('b', '*').replaceFirst("c$", "#")

If you need an one-line transformation chain:

def fix(s: String) =
 Some(s.replace('b', '*')).map(s => if(s.endsWith "c") s.init + "#" else s).get

or

def fix(s: String) =
 Some(s).filter(_ endsWith "c").map(_.init + '#').getOrElse(s).replace('b', '*')

(you can also use "match", but it takes more than one line)


As you really hope to see your "op" operator:

text.replace("b", "*") match {
    case t if (t.endsWith("c")) => t.stripSuffix("c") + ("#")
    case t => t
}


If you like regular expressions, you can do:

def fix(text: String) = {
  val EndsWithc = """(.*)c$""".r
  text.replace('b', '*') match { case EndsWithc(s) => s + "#" ; case t => t }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜