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
The trim() method is utilized to omit the leading and trailing spaces in the stated string. Return Type: It returns the stated string after removing all the white spaces.
String split() MethodThe split() method in Scala is used to split the given string into an array of strings using the separator passed as parameter. You can alternatively limit the total number of elements of the array using limit.
Using init() As we can see in the example, by calling the init() method, we remove the last character of the String. If you just need to remove a single element, this solution will be fine.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With