开发者

Why doesn't a string builder exist everywhere?

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜