On Friday, 26 September 2014 at 01:09:01 UTC, AsmMan wrote:
On Friday, 26 September 2014 at 00:53:24 UTC, ketmar via
Digitalmars-d-learn wrote:
On Fri, 26 Sep 2014 00:24:27 +0000
AsmMan via Digitalmars-d-learn
<digitalmars-d-learn@puremagic.com>
wrote:
It made me a bit confusing. How is the implementation of
string
comparasion in D?
"" has length of 0. null has length of 0. two strings without
content
are essentialy the same.
but null has length? what's null in D?
To reinforce what ketmar is saying:
strings in D are just `immutable(char)[]` ... a simple array of
immutable chars. All arrays are just (essentially) `struct Arr(T)
{ T* ptr; size_t length; }` ... so this differs from C# where
String is actually a class. So, when we talk about `string s =
null;`, the structure would look like `ptr = null; length = 0`.
You can still get the length out of a "nulled out string" (or any
array type for that matter). Obviously in C#, that'd give you a
null pointer exception since it's a class.
When you compare equality between two different arrays in D,
you're checking for if they have all of the same elements (thus,
ptr being different between two arrays is irrelevant). Trivially
any two strings with length 0 are equal, so there are 4 billion
equivalent empty strings in D (in 32-bit mode, and 2^64 in 64 bit
mode, of course).
So, if you want an empty string, you can do any one of:
`s = null;`
`s.length = 0;`
`s = "";`
and you'll be fine.