Baeldung Pro – Scala – NPI EA (cat = Baeldung on Scala)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

1. Overview

In this tutorial, we’ll show how to remove a substring from a String using only the Scala standard library. Given that Scala Strings are immutable by default the following operations actually create new Strings, and do not modify the original.

2. Using String.substring()

The first approach that we will cover will make use of the  String.substring() method. This method allows extracting a sub-section of a given String. This is achieved by using the two arguments that define the start and end index of the substring:

scala> val s = "Scala is very nice"
s: String = Scala is very nice

scala> s.substring(0,5)
res0: String = Scala

This example showed how easy it is to remove the substring that is a suffix of the given String. It is also very easy to do the same for a substring that is a prefix of the original String:

scala> s.substring(9,18)
res1: String = very nice

If we need to replace a substring that sits in the middle of the original String, we need a bit more work using this approach:

scala> s.substring(0,9) + s.substring(14,18)
res2: String = Scala is nice

Unfortunately, this approach is only easy if we know the index of the substring beforehand.

3. Using String.replace()

We can use a more generic approach by calling the String.replace() method:

scala> s.replace("very ", "")
res3: String = Scala is nice

Using this solution we do not need to know any index beforehand.

4. Conclusion

In this article, we learned how to remove a substring from a String using the Scala standard library. We first saw how we could extract the substring using the indexes. Then we moved to simply replace the substring with an empty string.