0

I have a string with with multiple length and breadth in the format length x breadth separated by commas like

300x250, 720x220, 560x80

I will like to convert this into two separate arrays one containing only length and another only breadth.

Expected output

length = Array(300,720, 560)

breadth = Array(250, 220, 80)

Any novel way to achieve it?

Govind Singh
  • 15,282
  • 14
  • 72
  • 106
mohit
  • 4,968
  • 1
  • 22
  • 39

3 Answers3

2

Using unzip over tupled values, as follows,

val dims = "300x250, 720x220, 560x80"

dims.split("\\W+").map { 
  s => val Array(a,b,_*) = s.split("x") 
       (a.toInt,b.toInt) }.unzip

Note the first split fetches words without need for trimming additional blank characters. In the second split we extract the first and second elements of the resulting Array.

elm
  • 20,117
  • 14
  • 67
  • 113
1

try this

scala> "300x250, 720x220, 560x80"
res0: String = 300x250, 720x220, 560x80

scala> res0.split(", ").map(_.split("x")(0).toInt)
res1: Array[Int] = Array(300, 720, 560)

scala> res0.split(", ").map(_.split("x")(1).toInt)
res2: Array[Int] = Array(250, 220, 80)
Govind Singh
  • 15,282
  • 14
  • 72
  • 106
1
val str = "300x250, 720x220, 560x80"
val regex = "(\\d+)x(\\d+)".r
val result = for {
  pair <- str.split(",\\s+").toList
  m <- regex.findAllMatchIn(pair)
} yield (m.group(1).toInt, m.group(2).toInt)

val (length, breadth) = result.unzip
Sergii Lagutin
  • 10,561
  • 1
  • 34
  • 43