Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Characters from the end of a String Scala

Tags:

string

scala

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.

like image 906
BefittingTheorem Avatar asked Nov 30 '09 21:11

BefittingTheorem


People also ask

How do I remove the last 3 characters from a string?

To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

How do you trim a string in Scala?

To remove blank spaces from a string, Scala provides a trim() method. The trim() will remove spaces from both sides, i.e. before the characters(leading) and from the end(trailing). The method doesn't accept any parameter and returns a string with spaces removed from it.


2 Answers

How about using dropRight, which works in 2.8:-

"abc!".dropRight(1) 

Which produces "abc"

like image 126
Don Mackenzie Avatar answered Sep 20 '22 19:09

Don Mackenzie


string.init // padding for the minimum 15 characters 
like image 41
Walter Chang Avatar answered Sep 18 '22 19:09

Walter Chang