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
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:
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.
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.