Smart way to convert a C string to a D string

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Aug 7 13:25:01 PDT 2013


On 8/7/13, andrea9940 <no at mail.plz> wrote:
> auto cstr2dstr(inout(char)* cstr)
> {
>      import core.stdc.string: strlen;
>      return cstr ? cstr[0 .. strlen(cstr)] : "";
> }

There's a small issue in your ternary operator, if 'cstr' is non-const
but null, you will end up returning an immutable rather than a mutable
string. In fact your return type will always be const because of this
ternary (mutable and immutable both implicitly convert to const). I
suggest changing it to this:

return cstr ? cstr[0 .. strlen(cstr)] : cstr[0 .. 0];

You can also use inout(char)[] on the return type, it documents the
function better (and this is how I caught the ternary issue as well).


More information about the Digitalmars-d-learn mailing list