Converting between string and const char*
Lars T. Kyllingstad
public at kyllingen.NOSPAMnet
Wed Mar 3 12:38:57 PST 2010
Robert Clipsham wrote:
> Hi all,
>
> I'm playing with D2/Phobos, and was wondering what the right way to
> convert between const char* and string is? In D1/Tango I could use
> toStringz() and fromStringz() from tango.stdc.stringz, I can only find
> an equivalent for toStringz in D2/Phobos though, in std.string. What can
> I use as a replacement to tango's fromStringz, or will I need to roll my
> own? I also tried using std.conv.to!(), but that doesn't seem to support
> converting between them.
>
> Robert
std.conv.to() can convert from const(char)* to string, at least, while
std.string.toStringz() converts the other way.
const(char)* s1 = "Hello";
string s2 = to!string(s1);
assert (s2 == "Hello");
const(char)* s3 = toStringz(s2);
assert (s3[0..5] == "Hello");
It's a bit weird that std.conv.to() only converts one way, but since
std.string is about to be removed from Phobos altogether, I assume it
will work both ways in the future.
-Lars
More information about the Digitalmars-d-learn
mailing list