Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 627
Felix Avatar asked May 06 '14 08:05

Felix


2 Answers

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.

like image 126
senia Avatar answered Nov 18 '22 16:11

senia


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
like image 3
serejja Avatar answered Nov 18 '22 14:11

serejja