如何在Scala中修剪字符串的开始和结束字符
对于",hello"
或"hello,"
等输入,我需要将输出作为"hello"
。
Scala中有内置方法可以做到这一点吗?
最佳答案
尝试
val str = " foo "
str.trim
看看the documentation。如果您也需要摆脱
,
字符,则可以尝试以下操作:str.stripPrefix(",").stripSuffix(",").trim
清理字符串前端的另一种方法是
val ignoreable = ", \t\r\n"
str.dropWhile(c => ignorable.indexOf(c) >= 0)
这也可以处理像
",,, ,,hello"
这样的字符串很好的是,这是一个很小的函数,该函数通过字符串从左到右一扫即可完成所有操作:
def stripAll(s: String, bad: String): String = {
@scala.annotation.tailrec def start(n: Int): String =
if (n == s.length) ""
else if (bad.indexOf(s.charAt(n)) < 0) end(n, s.length)
else start(1 + n)
@scala.annotation.tailrec def end(a: Int, n: Int): String =
if (n <= a) s.substring(a, n)
else if (bad.indexOf(s.charAt(n - 1)) < 0) s.substring(a, n)
else end(a, n - 1)
start(0)
}
使用方式
stripAll(stringToCleanUp, charactersToRemove)
例如。,
stripAll(" , , , hello , ,,,, ", " ,") => "hello"