문제

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top