1. Overview

In this tutorial, we’ll see how we can remove all whitespaces from a Scala String.

2. Remove All Whitespace From a String

Here’s the String we’ll be working with:

scala> val str = "  A String with empty  spaces "
str: String = "  A String with empty  spaces "

As we can see, there are whitespaces at the beginning, the end, and the middle of the String as well.

We expect the result to be “AStringwithemptyspaces” after removing all the whitespaces.

There are multiple ways to remove the existing whitespaces. Let’s go through two of them.

2.1. Using the filter() Method

The first solution we’ll look at is a naive approach. Given a String, we can manually exclude the whitespaces characters:

scala> str.filterNot(_.isWhitespace)
res0: String = AStringwithemptyspaces

This approach keeps the original String unmodified, returning a new one.

We should note that we make use of the Char.isWhitespace() method, which is a very useful method for our use case.

2.2. Using the replaceAll() Method

While the previous approach worked fine, it’s not straightforward. Instead, we can use the String.replaceAll() method:

scala> str.replaceAll(" ", "")
res1: String = AStringwithemptyspaces

This approach remove all the empty spaces. Just like the previous approach, the original String is kept unmodified.

3. Conclusion

In this article, we saw how to remove all the whitespace from a Scala String.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.