开发者

Scala: String Chomp

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开发者_Go百科


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


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]


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜