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:
If you need an one-line transformation chain:
or
(you can also use “match”, but it takes more than one line)