从字符串 Scala 的末尾删除字符

在 Scala 中,删除字符串末尾最后一个字符的最简单方法是什么?

我发现 Rubys String 类有一些非常有用的方法,比如 快点。我会用“ oddoneoutz”。在 Scala 中的 headOption,但是它被折旧了。我不想过于复杂:

string.slice(0, string.length - 1)

请告诉我有一个很好的简单的方法,像印章的东西这么普通。

82280 次浏览
string.reverse.substring(1).reverse

That's basically chop, right? If you're longing for a chop method, why not write your own StringUtils library and include it in your projects until you find a suitable, more generic replacement?

Hey, look, it's in commons.

Apache Commons StringUtils.

How about using dropRight, which works in 2.8:-

"abc!".dropRight(1)

Which produces "abc"

val str = "Hello world!"
str take (str.length - 1) mkString
string.init // padding for the minimum 15 characters

If you want the most efficient solution than just use:

str.substring(0, str.length - 1)

If you want just to remove the last character use .dropRight(1). Alternatively, if you want to remove a specific ending character you may want to use a match pattern as

val s: String = "hello!"
val sClean: String = s.takeRight(1) match {
case "!" => s.dropRight(1)
case _   => s
}