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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With