Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert character in Scala String

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

like image 381
elm Avatar asked Aug 11 '14 07:08

elm


3 Answers

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

like image 119
Xavier Guihot Avatar answered Oct 31 '22 17:10

Xavier Guihot


Try this

val (fst, snd) = s.splitAt(2)
fst + 'c' + snd
like image 39
tiran Avatar answered Oct 31 '22 18:10

tiran


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

like image 2
elm Avatar answered Oct 31 '22 16:10

elm