Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take string and extract first word and comma separate in scala?

Tags:

scala

I have the following string:

"year   string  
temperature int
quality int" 

I need to extract the first word from each line and comma separate it ( so it should be "year, temperature, quality"). How do I do this in scala? I tried using regexes and split to create an array of strings, but eclipse is barking at me when I try to iterate over the array.

like image 786
vsingal5 Avatar asked Jul 23 '13 00:07

vsingal5


1 Answers

val s = """year   string
temperature int
quality int"""

s.split("\n").map(_.split("\\s+")(0)).mkString(", ")
// res0: String = year, temperature, quality

This splits the string s on newline characters to get an array of lines. Then, for each line, it splits the line on whitespace, and takes the first element of the resulting array, which is the first word. Last, it makes a string out of the array of first words by concatenating them with commas in between.

Just to spell out the steps involved here, this is equivalent to the last line above:

val lines = s.split("\n")
val firstWords = lines.map(_.split("\\s+")(0))
firstWords.mkString(", ")
like image 102
dhg Avatar answered Nov 10 '22 00:11

dhg