A Scala String chomp (or chop) function

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.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.