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.
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(", ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With