How to distinguish char * to a string in D?

I have a standard char pointer that I am trying to pass 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 on how to distinguish char * from string in D?

+6
source share
2 answers

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); } 
+14
source

If you know the exact length, you can do this:

 immutable(char)* cptr = obj.SomeSource(); int len = obj.SomeLength(); string str = cptr[0..len]; 

In some cases (for example, if the string contains \0 ), which is necessary.

+3
source

Source: https://habr.com/ru/post/905667/


All Articles