scalacollections

Transform a sequence of strings containing delimiter


I have a sequence of strings which may or may not contain a delimiter

val words = Seq("1 $ cake", "2biscuit", "3brownie", "4 $ honey")

I would need to create a resulting sequence from above - if '$' exists , take the preceding bit after trimming, else the whole string.

val res = Seq("1", "2biscuit", "3brownie", "4")

I am looking for a safe and efficient solution to do this in a single pass.


Solution

  • If you want to change every element in a sequence you need to use map, which applies a function to every element.

    If you want to take everything before the $ in a string you need to use takeWhile, which keeps taking characters from the string while they are not a given character.

    Edit: Use trim to remove surrounding spaces.

    Putting them together gives the solution:

    words.map(_.takeWhile(_ != '$').trim)