david hol david hol - 3 months ago 15
Scala Question

How to split and remove empty spaces before get the result

I have this

String
:

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
trim
after the split can i do it before ?

Answer

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.