I sort of understand the motivation for a String Builder class, but do all languages have one? Should they? I'm thinking specifically of PHP, Perl, Python, and Ruby. I know C# and Java do. If the others don't, why not? Do they not suffer from the same implementation problem? Or do they not care?
+7
A:
Not all languages have a String builder.
C, for example, doesn't even have strings.
In C++, std::strings are mutable -- they can be changed, so there is no real need for a separate string builder class.
In C# (and the rest of .NET), string are immutable - they cannot be changed, only replaced This leads to the problem causing the need for StringBuilder.
Technically, .NET strings are reference types pretending to be value types. This was done to make they act more like the native types (int, float, decimal).
James Curran
2010-08-12 19:10:31
Same deal for Java - Strings are immutable, so concatenation operations actually involve creating new, ever larger objects at each operation.
Brabster
2010-08-12 19:13:13
So... would it be okay to say the mutability of strings dictates the necessity for the string builder pattern?
Mark Canlas
2010-08-12 19:14:28
Python's strings are immutable, but it doesn't require a StringBuilder analog. When you write a=a+'foo', it creates a new string option containing a+'foo', free()s the old contents of a, and modifies a to point at the new object.
Just Some Guy
2010-08-12 19:16:29
@JustSomeGuy: C# supports that as well, but to reduce the number of temporary strings (which must be collected by the GC) .NET also offers a StringBuilder class, which doesn't create a new instance for each modification.
Brian Rasmussen
2010-08-12 19:18:58
@Brian: I guess the Python equivalent would be something like creating a list of values, then joining them together: print ''.join(valuelist)
Just Some Guy
2010-08-12 20:57:20
A:
There is no need in string builders when string streams exist - file-like objects to construct strings.
For example, Python has StringIO
:
from cStringIO import StringIO
sio = StringIO()
sio.write("Hello")
sio.write(" world!!")
sio.write(111)
sio.write('!')
print sio.getvalue()
Hello world!!111!
Ruby has its own StringIO too. In C++, the equivalent is std::stringstream
.
grep
2010-08-12 19:24:51
@James Curran ~ The point is (I think) that it's the same as a stringbuilder but a different name ...
drachenstern
2010-08-12 19:52:40