tags:

views:

287

answers:

4

Hi,

does Scala have an API to do a "chomp" on a String? Preferrably, I would like to convert a string "abcd \n" to "abcd"

Thanks Ajay

+2  A: 

Why not use Apache Commons Lang and the StringUtils.chomp() function ? One of the great things about Scala is that you can leverage off existing Java libraries.

Brian Agnew
That sucks. I would expect them to provide chomp support out of the box.
ajay
+7  A: 

There's java.lang.String.trim(), but that also removes leading whitespace. There's also RichString.stripLineEnd, but that only removes \n and \r.

sepp2k
+3  A: 

If you don't want to use Apache Commons Lang, you can roll your own, along these lines.

scala> def chomp(text: String) = text.reverse.dropWhile(" \n\r".contains(_)).reverse
chomp: (text: String)String

scala> "[" + chomp(" a b cd\r \n") + "]"
res28: java.lang.String = [ a b cd]
retronym
It gives me back ArrayBuffer. Not string
ajay
I was using Scala 2.8
retronym
+2  A: 

There is in fact an out of the box support for chomp1

scala> val input = "abcd\n"
input: java.lang.String =
abcd


scala> "[%s]".format(input)
res2: String =
[abcd
]

scala> val chomped = input.stripLineEnd
chomped: String = abcd

scala> "[%s]".format(chomped)
res3: String = [abcd]

1 for some definition of chomp; really same answer as sepp2k but showing how to use it on String

huynhjl