david hol david hol - 1 year ago 52
Scala Question

How to split and remove empty spaces before get the result

I have this


val str = "9617 / 20634"

So after split i want to parse only the 2 values
9617 & 20634
in order to calculate percentage.
So instead of
after the split can i do it before ?

Answer Source

It is easier to remove spaces after the split than before. Unless you are expected to trim it before, here is a simpler way of doing it.

val Array(x, y) = "9617 / 20634".split("/").map(_.trim.toFloat)
val p = x / y * 100

Values are converted to Float to prevent integer division leading to 0. The val Array(x,y) = ... statement is just another way of calling unapplySeq of the Array object.