In this tutorial, we’ll see how we can remove characters from the end of a String in Scala.
2. Remove Characters from the End of a String
There are a few different approaches to achieving this. Let’s go through them.
2.1. Using substring()
The first approach uses a widely known String method: substring(). This method allows extracting a sub-section of a given String by passing two arguments to define the start and end index of the substring:
scala> val s = "my string" val s: String = my string scala> var charsToRemove = 3 var charsToRemove: Int = 3 scala> s.substring(0, s.length - charsToRemove) val res0: String = my str scala> var charsToRemove = 1 var charsToRemove: Int = 1 scala> s.substring(0, s.length - charsToRemove) val res1: String = my strin
By specifying 0 as the first argument, we’re able to select a substring from the start until the specified index in the second parameter.
2.2. Using dropRight()
Another possible solution is to use the fact that a String is like a sequence of chars. Due to this, we can use the dropRight() method, which removes the N far most chars:
scala> val s = "my string" val s: String = my string scala> s.dropRight(3) val res0: String = my str scala> s.dropRight(1) val res1: String = my strin
This method just needs to receive as an argument the number of chars to remove, and it works perfectly.
2.3. Using init()
This other approach is not as widely known, but it can be useful to remove just the last char of the String (a bit like the head method, but the opposite):
scala> val s = "my string" val s: String = my string scala> s.init val res0: String = my strin
As we can see in the example, by calling the init() method, we remove the last character of the String. If you just need to remove a single element, this solution will be fine. If you need to remove more characters, you must look at one of the other approaches described before.
2.4. Using Apache Commons StringUtils
scala> StringUtils.chop("abc") val res0: String = ab
The method behaves very similarly to the init() method we saw before, as it removes the last character of the String. This lib was written in Java, so it may not be as idiomatic, but it still shows very useful.
In this article, we saw a few different approaches on how to remove characters from the end of a String in Scala.