By Alvin Alexander. Last updated: April 11, 2018
Just a quick note today that if you split a CSV string in Scala, you should also (immediately) do a trim
on each resulting element in the array. The Scala REPL shows why this is necessary:
scala> val tags = "foo, bar, baz, boom baz"
tags: String = foo, bar, baz, boom baz
scala> tags.split(",")
res0: Array[String] = Array(foo, " bar", " baz", " boom baz")
scala> tags.split(",").map(_.trim)
res1: Array[String] = Array(foo, bar, baz, boom baz)
As shown with res0
, if you don’t do a trim
on the elements they can end up with blank spaces in them. The second example shows how to call the string trim
function to trim each string/substring that’s found in the original CSV string.