How to cast a char* to string in D?

2019-02-17 11:03发布

问题:

I have a standard char pointer which im trying to cast to a string.

// string to char*
char *x = cast(char*)("Hello World\0");

// char* to string?
string x = cast(string)x;
string x = cast(immutable(char)[])x;

Error!

Any ideas how to cast a char* to a string in D?

回答1:

Use std.conv.to to convert from char* to string. Use std.string.toStringZ to go the other way.

import std.string;
import std.stdio;
import std.conv;

void main()
{
    immutable(char)* x = "Hello World".toStringz();
    auto s = to!string(x);
    writeln(s);
}


回答2:

If you know the exact length you can do this:

immutable(char)* cptr = obj.SomeSource();
int len = obj.SomeLength();

string str = cptr[0..len];

For some cases (like if the string contains \0) that is needed.