Smart way to convert a C string to a D string
John Colvin
john.loughran.colvin at gmail.com
Wed Aug 7 13:51:33 PDT 2013
On Wednesday, 7 August 2013 at 18:50:21 UTC, andrea9940 wrote:
> Hi, I have written a function to convert a C string to a D
> string.
> I did not use to!string because it allocates a new string while
> what I want is a dynamic array of type char[] pointing to the C
> string.
>
> auto cstr2dstr(inout(char)* cstr)
> {
> import core.stdc.string: strlen;
> return cstr ? cstr[0 .. strlen(cstr)] : "";
> }
>
> As D newbie I'd like to know if this is the correct usage of
> inout (it is needed to accept without distinction char*,
> const(char)* and immutable(char)* right ?) and if there is
> already a function in the standard D library which do that
> conversion.
Another way of doing this is lazily with a range. *Very*
basically done, just for char* and read-only:
struct Cstring
{
size_t i = 0;
char* str;
this(char* s)
{
str = s;
}
@property bool empty()
{
return str[i] == '\0';
}
@property char front()
{
return str[i];
}
void popFront()
{
++i;
}
}
More information about the Digitalmars-d-learn
mailing list