1

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.

1
  • 3
    What have you tried already? Why isn't it just a map? Commented May 3 at 6:52

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

4 Comments

And add a trim after the takeWhile as per OP requirement.
@GaëlJ Thanks, I missed that bit!
@GaëlJ Well, literally OP didn't ask to trim when there is no dollar sign ("else the whole string") :)
@DmytroMitin My code trims the start of the string which arguably is also wrong. But I'm not convinced that the details of the trimming are the key part of the question :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.