9

For any given String, for instance

val s = "abde"

how to insert a character c: Char at position 2, after b ?

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.)

Machavity
  • 30,841
  • 27
  • 92
  • 100
elm
  • 20,117
  • 14
  • 67
  • 113
  • Get the substrings `[0,2)` and `[2,length)`, and then do `sub1 + c + sub2` – Kvass Aug 11 '14 at 07:12
  • `String sub1 = s.substring(0,2)` gives you "ab" – Kvass Aug 11 '14 at 07:13
  • 2
    Don't forget that strings are immutable – yǝsʞǝla Aug 11 '14 at 07:25
  • 3
    @enzyme generally speaking, if you're doing it a lot and you have long strings, [rope](https://en.wikipedia.org/wiki/Rope_(computer_science)) is the right data structure. IIRC, Scala has no such thing in standard library, though. – om-nom-nom Aug 11 '14 at 07:41
  • @om-nom-nom thanks! looks like the way to go... looking for Scala rope implementations... – elm Aug 11 '14 at 08:10

3 Answers3

14

We can use the patch method on Strings in order to insert a String at a specific index:

"abde".patch(2, "c", 0)
// "abcde"

This:

  • drops 0 (third parameter) elements at index 2

  • inserts "c" at index 2

which in other words means patching 0 elements at index 2 with the string "c".

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
6

Try this

val (fst, snd) = s.splitAt(2)
fst + 'c' + snd
tiran
  • 2,389
  • 1
  • 16
  • 28
  • 1
    not sure whether `Vector`s suit for your requirement. check performance characteristics in [here](http://www.scala-lang.org/docu/files/collections-api/collections.html) – tiran Aug 11 '14 at 08:39
2

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

elm
  • 20,117
  • 14
  • 67
  • 113