How to cast a char* to string in D?

萝らか妹 提交于 2019-12-01 02:25:16

问题


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.



来源:https://stackoverflow.com/questions/8811806/how-to-cast-a-char-to-string-in-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!