Insert character in Scala String
Solution 1
Rope data structure proves a valid alternative to String
and StringBuffer
for heavy manipulation in (very) large strings, especially in regard to insertions and deletions.
Scalaz includes class Rope[A]
(see API and Rope.scala) and class WrappedRope[A]
(see API) with a plethora of operations on rope strings.
Implementations in Java include http://ahmadsoft.org/ropes/. A benchmarking study for this Java implementation may be found at http://www.ibm.com/developerworks/library/j-ropes/ .
A publication on ropes as an alternative to strings may be found at http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.14.9450&rep=rep1&type=pdf
Solution 2
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"
.
Solution 3
Try this
val (fst, snd) = s.splitAt(2)
fst + 'c' + snd
elm
Updated on June 04, 2022Comments
-
elm about 2 years
For any given
String
, for instanceval s = "abde"
how to insert a character
c: Char
at position 2, afterb
?Update
Which Scala collection to consider for multiple efficient insertions and deletions at random positions ? (Assuming that a
String
may be transformed into that collection.)-
Kvass almost 10 yearsGet the substrings
[0,2)
and[2,length)
, and then dosub1 + c + sub2
-
Kvass almost 10 years
String sub1 = s.substring(0,2)
gives you "ab" -
yǝsʞǝla almost 10 yearsDon't forget that strings are immutable
-
om-nom-nom almost 10 years@enzyme generally speaking, if you're doing it a lot and you have long strings, rope is the right data structure. IIRC, Scala has no such thing in standard library, though.
-
elm almost 10 years@om-nom-nom thanks! looks like the way to go... looking for Scala rope implementations...
-
-
tiran almost 10 yearsnot sure whether
Vector
s suit for your requirement. check performance characteristics in here