1. Overview
In this tutorial, we’ll see how to insert a character at a specific index in a Scala String.
2. Using String Concatenation
The first approach we’ll explore is using naive String manipulation by getting the desired substrings and concatenating all elements.
For instance, let’s add the character ‘z‘ to the string ‘Hello‘ after the index 2 (i.e., after letter ‘e‘):
scala> val s = "Hello"
s: String = Hello
scala> val idx = 2
idx: Int = 2
scala> s.substring(0,idx) + 'z' + s.substring(idx, 5)
res0: String = Hezllo
We start by getting the initial part of the original string: We extract the substring until the index where we want to insert the new character is reached. Then, we add up the new character and the remaining suffix of the original string.
Notably, the original string remains unchanged, and we return a new string.
3. Using the String.patch() Method
The previous solution has a bit of boilerplate. It’s also easy to introduce a bug when doing String manipulation manually. Fortunately, Scala contains a String.patch() method that makes this job easier:
scala> s.patch(idx, "z", 0)
res0: String = Hezllo
The String.patch() method receives three parameters: the index where to insert the new characters, the new characters, and how many characters to remove from the index. This last parameter may be unexpected, but we can read the method signature as “At index 2, let’s remove 0 characters, and then add the new substring ‘z‘.”
Let’s see in practice how this last parameter influences the output:
scala> s.patch(2, "z", 0)
res0: String = Hezllo
scala> s.patch(2, "z", 1)
res1: String = Hezlo
scala> s.patch(2, "z", 2)
res2: String = Hezo
In the second example, the first ‘L‘ character was removed, i.e., the first element after index 2. In the second example, we remove the two characters after index 2, i.e., the elements at index 2 and 3, which were both ‘L‘ characters.
Just like in the previous approach, the original string remains unchanged, and we return a new string.
4. Conclusion
In this article, we saw how to insert a new character at a specific String index.
We started with a naive approach using basic String manipulation and concatenation, and then we saw the Scala String.patch() method.