Home

StringBuilder

StringBuilder

Scala strings are immutable. Sometimes we need a mutable string, typically because we want to build up a long string from small pieces, for instance in a loop. The StringBuilder class is useful as a mutable string that can grow efficiently (it is implemented using the doubling strategy). A StringBuilder object B can mostly be used like a string, but it is mutable, and you can append to it:

In addition, StringBuilder provides all the common methods of sequences—a StringBuilder is a sequence of Char elements.

For instance:

scala> val B = new StringBuilder
B: StringBuilder = 
scala> B ++= "Hello"
res0: B.type = Hello
scala> B += ' '
res1: B.type = Hello 
scala> B ++= "World"
res2: B.type = Hello World
scala> B.delete(1,2)
res3: StringBuilder = Hllo World
scala> B.insert(5, "CS206 ")
res4: StringBuilder = Hllo CS206 World
scala> B(1) = 'e'
scala> B
res5: StringBuilder = Helo CS206 World
scala> B.toString
res6: java.lang.String = Helo CS206 World