By Alvin Alexander. Last updated: June 4, 2016
Scala string FAQ: Does Scala have a String method like chomp or chop that you find in Perl?
If you're using Scala and want a string chomp or chop method that you're used to in languages like Perl to remove end of line characters, the stripLineEnd method will do what you want, as shown in the REPL:
scala> val a = "foo\n" a: String = "foo " scala> a.stripLineEnd res0: String = foo scala> val b = "bar" b: String = bar scala> b.stripLineEnd res1: String = bar
This method can be found in the Scala StringOps class, which you can find here:
- http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html#scala.collection.immutable.StringOps
Note that this behavior is different than the trim method on the String class, which trims blank spaces from the beginning and end of a string.
You can also use stripLineEnd to define your own chomp or chop function, like this:
def chomp(s: String) = s.stripLineEnd
You can then call the function with a String, like this:
scala> chomp(a) res2: String = foo scala> chomp(b) res3: String = bar
If you're looking for a Scala String chop/chomp method, I hope this has been helpful.

