views:

425

answers:

4

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.

+1  A: 
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.

Stefan Kendall
It sure is Stefan. I was hoping for a method that when you look at the code, you understand what is going on :) What I'm saying is: For something as simple as "remove last character from string" reverse.substring(1).reverse is misleading. Thanks for the reply
Brian Heylin
Plus you'd need to wrap the string into a StringBuilder to get a reverse method.
Fabian Steeg
The first part was mostly a joke :P. Any Java programmer looking at your Scala should be familiar with StringUtils, or at least know of the Apache Commons library to see the import and not be offended. Commons is useful, and it should be used where possible. I've found that most projects include commons at some point, so there's generally no expense to using the library.You could even alias StringUtils as su in your scala programs and refer to it as su.chop(str), which is pretty succinct and not as sucky as using substring.
Stefan Kendall
Too bad an implicit for StringUtils would be a lot of work. Just shows the mismatch between the way Scala users and Java users think about extension methods.
Ken Bloom
import org.apache.commons.blah.{StringUtils => su} is a lot of work? Ideally, you'd be deploying to an environment with these libraries already established, as I've said.
Stefan Kendall
+6  A: 

How about using dropRight, which works in 2.8:-

"abc!".dropRight(1)

Which produces "abc"

Don Mackenzie
The most terse I can come up with for 2.7 is "abc!".split(".$)(0)
Don Mackenzie
Oops I mean "abc!".split(".$")(0)
Don Mackenzie
Excellent Thanks Don, I'll have to upgrade to 2.8 :)
Brian Heylin
+2  A: 
val str = "Hello world!"
str take (str.length - 1) mkString
David Winslow
+1  A: 
string.init // padding for the minimum 15 characters
Walter Chang
Thanks Walter, that's exactly the method I thought Scala would have. Again all these nice methods are 2.8 only, so upgrade here I come :)
Brian Heylin