In java, I can do it with commons-lang
:
StringUtils.stripEnd(" abc \t", null) // => " abc"
I want to know if there is any built-in method to do this in scala, or how to do it in scala without any 3rd-party dependencies?
Trim() Removes all leading and trailing white-space characters from the current string. Trim(Char) Removes all leading and trailing instances of a character from the current string. Trim(Char[]) Removes all leading and trailing occurrences of a set of characters specified in an array from the current string.
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.
You can do it with a regex:
" string ".replaceAll("\\s+$", "");
res0: java.lang.String = " string"
Another possible way is to use method dropWhile
from rich String
class named StringOps
scala> val y = " abcd ".reverse.dropWhile(_ == ' ').reverse
y: String = " abcd"
If you need to trim spaces from the beginning of string just remove reverse
methods:
scala> val y = " abcd ".dropWhile(_ == ' ')
y: String = "abcd "
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