A D-style string.
A C-style null-terminated string equivalent to s. s must not contain embedded '\0''s as any C function will treat the first '\0' that it sees as the end of the string. If s.empty is true, then a string containing only '\0' is returned.
Important Note: When passing a char* to a C function, and the C function keeps it around for any reason, make sure that you keep a reference to it in your D code. Otherwise, it may become invalid during a garbage collection cycle and cause a nasty bug when the C code tries to use it.
1 import core.stdc.string : strlen; 2 import std.conv : to; 3 4 auto p = toStringz("foo"); 5 assert(strlen(p) == 3); 6 const(char)[] foo = "abbzxyzzy"; 7 p = toStringz(foo[3 .. 5]); 8 assert(strlen(p) == 2); 9 10 string test = ""; 11 p = toStringz(test); 12 assert(*p == 0); 13 14 test = "\0"; 15 p = toStringz(test); 16 assert(*p == 0); 17 18 test = "foo\0"; 19 p = toStringz(test); 20 assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0); 21 22 const string test2 = ""; 23 p = toStringz(test2); 24 assert(*p == 0);