The Scala String
method (in class StringOps
) stripMargin
removes leading whitespace from each line of a multi-line String
up to and including the pipe (|
) character (or other designated delimiter).
Is there an equivalent method to remove trailing whitespace from each line?
I did a quick look through the Scaladocs, but could not find one.
What is trim() in Scala? The trim() method is used to remove all the leading and trailing spaces that are present in the string. For example, if the string looks like, " Hello World " then there is a lot of empty space before the term “Hello” and after the term “World”. The method trim() is used to remove these spaces.
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
strip(): returns a new string after removing any leading and trailing whitespaces including tabs ( \t ). rstrip(): returns a new string with trailing whitespace removed. It's easier to remember as removing white spaces from “right” side of the string.
stripMargin ( '#' ) All of these approaches yield the same result, a multiline string with each line of the string left justified: Four score and seven years ago. This results in a true multiline string, with a hidden \n character after the word “and” in the first line.
Java String
method trim
removes whitespace from beginning and end:
scala> println("<"+" abc ".trim+">") <abc>
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