Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: String Chomp

Tags:

scala

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

like image 464
user855 Avatar asked Feb 15 '10 22:02

user855


People also ask

How do you cut a space in Scala?

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.

How do you split text in Scala?

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.

How do you remove the last character of a string in Scala?

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.


2 Answers

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

like image 173
sepp2k Avatar answered Sep 28 '22 14:09

sepp2k


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]
like image 28
retronym Avatar answered Sep 28 '22 13:09

retronym