what exactly is string length?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Apr 2 05:00:04 UTC 2021


On Fri, Apr 02, 2021 at 04:32:53AM +0000, mw via Digitalmars-d-learn wrote:
[...]
> ---
> import std;
> import std.conv : text;
> 
> 
> void main()
> {
>     char[6] s;
>     s = "abc";
>     writeln(s, s.length);  // abc6, ok it's the static array's length
> 
>     string t = text("head-", s, "-tail");
>     writeln(t, t.length);  // head-abc-tail16, why?
> }
> ---
> 
> Why the last output is 16 instead of 13, t's type is string here.

Because `s` contains 6 chars, and you only assigned 3 of them, so there
are 3 trailing null bytes that are inserted before "-tail". Null bytes
don't print anything, so you don't see them when printed as a string,
but if you cast it to ubyte[], you will see them:

	writefln("%(%02X %)", t);
	// Prints: 68 65 61 64 2D 61 62 63 00 00 00 2D 74 61 69 6C

Remember, this is D, not C. Strings are not terminated by nulls, so
appending the static array will append all 6 chars, including the nulls.


T

-- 
Holding a grudge is like drinking poison and hoping the other person dies. -- seen on the 'Net


More information about the Digitalmars-d-learn mailing list