Scala String trimming by a set of characters

scala, string

Solution

Scala has a `dropWhile` that solves half of the problem. It also has a `dropRight` that's an analog to `drop` for the right end of the collection. Unfortunately it doesn't have a `dropWhileRight`, though, so you have to get creative.

If you don't particularly care about efficiency, you can just drop the characters off the left end, reverse, repeat, and reverse again:

scala> "untidy stringnu".dropWhile(s).reverse.dropWhile(s).reverse
res0: String = tidy string

If you're sure that's going to be a bottleneck in your program (hint: it's probably not), you'll want some kind of imperative solution.

Problem

Given any set of (trailing) characters, for instance ``` val s = "un".toSet ``` how to trim a string by `s`, namely, ``` "untidy stringnu".trimBy(s) res: String = tidy string ```

Original source