Remove Characters from the end of a String Scala

StringScala

String Problem Overview


What is the simplest method to remove the last character from the end of a String in Scala?

I find Rubys String class has some very useful methods like chop. I would have used "oddoneoutz".headOption in Scala, but it is depreciated. I don't want to get into the overly complex:

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

Please someone tell me there is a nice simple method like chop for something this common.

String Solutions


Solution 1 - String

How about using dropRight, which works in 2.8:-

"abc!".dropRight(1)

Which produces "abc"

Solution 2 - String

string.init // padding for the minimum 15 characters

Solution 3 - String

val str = "Hello world!"
str take (str.length - 1) mkString

Solution 4 - String

If you want the most efficient solution than just use:

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

Solution 5 - String

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.

Solution 6 - String

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBefittingTheoremView Question on Stackoverflow
Solution 1 - StringDon MackenzieView Answer on Stackoverflow
Solution 2 - StringWalter ChangView Answer on Stackoverflow
Solution 3 - StringDavid WinslowView Answer on Stackoverflow
Solution 4 - StringAndriy PlokhotnyukView Answer on Stackoverflow
Solution 5 - StringStefan KendallView Answer on Stackoverflow
Solution 6 - StringGaluoisesView Answer on Stackoverflow