针对任何一组(尾部)字符,例如
val s = "un".toSet
如何通过s
裁剪字符串,即,
"untidy stringnu".trimBy(s)
res: String = tidy string
针对任何一组(尾部)字符,例如
val s = "un".toSet
如何通过s
裁剪字符串,即,
"untidy stringnu".trimBy(s)
res: String = tidy string
dropWhile
可以解决问题的一半。它还有一个dropRight
,它是集合右端的drop
的类比。不幸的是,它没有dropWhileRight
,所以你必须富有创意。scala> "untidy stringnu".dropWhile(s).reverse.dropWhile(s).reverse
res0: String = tidy string
如果你确信这会成为程序的瓶颈(提示:可能不是),你需要一种命令式解决方案。
scala> val s = "undo"
s: String = undo
scala> val r = s"""[$s]*(.*?)[$s]*""".r
r: scala.util.matching.Regex = [undo]*(.*?)[undo]*
scala> def f(x: String) = x match { case r(y) => y case z => z }
f: (x: String)String
scala> f("nodu some string here...donuts are goodun")
res0: String = " some string here...donuts are g"
scala> f("undoundo")
res1: String = ""
或者
scala> val r = s"""[$s]*(?:(.*[^$s])[$s]*|$$)""".r
r: scala.util.matching.Regex = [undo]*(?:(.*[^undo])[undo]*|$)
scala> def f(x: String) = x match { case r(null) => "" case r(y) => y case z => z }
f: (x: String)String