Insert character in Scala String
Try this
val (fst, snd) = s.splitAt(2)
fst + 'c' + snd
We can use the patch
method on String
s in order to insert a String
at a specific index:
"abde".patch(2, "c", 0)
// "abcde"
This:
drops
0
(third parameter) elements at index2
inserts
"c"
at index2
which in other words means patching 0 elements at index 2 with the string "c"
.