Felix
Felix

Reputation: 8495

Is there a combination of takeWhile,dropWhile in Scala?

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?

Upvotes: 22

Views: 5503

Answers (2)

senia
senia

Reputation: 38045

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.

Upvotes: 50

serejja
serejja

Reputation: 23881

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

Upvotes: 3

Related Questions