Dust009 Dust009 - 2 months ago 10
Scala Question

Scala: Splitting a string into two integers

This is my current code. I want to split a string into two integers and stock them into variables.

val line = "1 2"
var a = 0
var b = 0
val c = line.split(" ") match { case Array(x,y) => (x.toInt, y.toInt) }
a = c._1
b = c._2


Is there any way to do something like this in Scala ? This is much more compact.

(a,b) = line.split(" ") match { case Array(x,y) => (x.toInt, y.toInt) }


The expression line.split(" ") match { case Array(x,y) => (x.toInt, y.toInt) } returns a tupple of integers so I thought directly linked the two integers with the variables a and b would work.

Answer

This is much more compact and clean

val Array(a,b) = line.split("\\s+").map(_.toInt)

Following code works even if there are more numbers in the string

val Array(a, b, _*) = line split "\\s+" map(_ toInt)

dot optional

val Array(a,b) = line split("\\s+") map(_.toInt)

what about this ?

val Array(a,b) = line split "\\s+" map(_ toInt)

Scala REPL

scala> val line = "1 2"
line: String = "1 2"
scala> val Array(a,b) = line.split("\\s+").map(_.toInt)
a: Int = 1
b: Int = 2

scala> val line = "1 2 3  4"
line: String = "1 2 3  4"
scala> val Array(a, b, _*) = line split "\\s+" map(_ toInt)
a: Int = 1
b: Int = 2
Comments