Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim ending blanks of a string?

Tags:

scala

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?

like image 229
Freewind Avatar asked Jul 17 '11 14:07

Freewind


People also ask

How do you trim empty spaces in a string?

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.

How do you remove leading and trailing blanks?

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.


2 Answers

You can do it with a regex:

"  string  ".replaceAll("\\s+$", "");
res0: java.lang.String = "  string"
like image 151
Jonas Avatar answered Sep 22 '22 05:09

Jonas


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   "
like image 32
om-nom-nom Avatar answered Sep 25 '22 05:09

om-nom-nom