Question

In Scala, I want to split a string at a specific character like so:

scala> val s = "abba.aadd" 
s: String = abba.aadd
scala> val (beforeDot,afterDot) = (s takeWhile (_!='.'), s dropWhile (_!='.'))
beforeDot: String = abba
afterDot: String = .aadd

This solution is slightly inefficient (maybe not asymptotically), but I have the feeling something like this might exist in the standard library already. Any ideas?

Was it helpful?

Solution

There is a span method:

scala> val (beforeDot, afterDot) = s.span{ _ != '.' }
beforeDot: String = abba
afterDot: String = .aadd

From the Scala documentation:

c span p is equivalent to (but possibly more efficient than) (c takeWhile p, c dropWhile p), provided the evaluation of the predicate p does not cause any side-effects.

OTHER TIPS

You can use splitAt for what you want:

val s = "abba.aadd"
val (before, after) = s.splitAt(s.indexOf('.'))

Output:

before: String = abba
after: String = .aadd
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top