Why can I write to string literals?
D does not have const like C++ does to protect string literals,
but in D you're supposed to use copy on write (COW), so it should not be an issue.
Do not write to memory that you did not allocate.
char isn't always working as expected with C functions
D's strings aren't necessarily null-terminated.
If you want to pass your char to a C function, use the function toStringz
(need to import std.string).
char hi = "hello world";
char slice = hi[0 .. 5];
Another thing to keep in mind is that because a char is laid out with the length first
and a pointer to the data second, you can use the %.*s format with printf:
printf("1 = '%.*s', 2 = '%.*s'\n", hi, slice);
But how can I easily use my D string with D and C functions?
Because toStringz adds a null byte to the returned string
if necessary, you can save the value like so:
slice = toStringz(slice)[0 .. slice.length];
Now you can pass slice to functions expecting C strings, and to functions
expecting D strings! Just remember that you would need to do this each time you
get a new slice; and you shouldn't be using C functions that much.
Why is a null char ==
I've seen a lot of flaming on this one.
The values are being compared, not addresses. Just like the C code:
memcmp("", NULL, 0);
If you want to compare the addresses, use the is
operator. Note: the is
operator does not compare
the string lengths.
Q. Why not use the template syntax the other C style languages use?
A. D's new template syntax makes it easier to parse the source
code without having to know about the code's meaning. That is, how would you know if
the < was a less-than operator or for a template? This also solves the minor problem
when using a template as a template parameter.
Is the >> right-shift or a template? Add a space, sure. Here's the D way:
Q. What makes the ! operator so easy to parse? Don't we
already use it as the logical not operator?
A. That would be a unary operator. The template ! is binary,
a ! b