how to convert a c string to a d string?

拟墨画扇 提交于 2021-02-07 11:46:11

问题


This is so simple I'm embarrassed to ask, but how do you convert a c string to a d string in D2?

I've got two use cases.

string convert( const(char)* c_str );
string convert( const(char)* c_str, size_t length );

回答1:


  1. Use std.string.toString(char*) (D1/Phobos) or std.conv.to!(string) (D2):

    // D1
    import std.string; 
    ... 
    string s = toString(c_str);
    
    // D2
    import std.conv;
    ...
    string s = to!(string)(c_str);
    
  2. Slice the pointer:

    string s = c_str[0..len];
    

    (you can't use "length" because it has a special meaning with the slice syntax).

Both will return a slice over the C string (thus, a reference and not a copy). Use the .dup property to create a copy.

Note that D strings are considered to be in UTF-8 encoding. If your string is in another encoding, you'll need to convert it (e.g. using the functions from std.windows.charset).



来源:https://stackoverflow.com/questions/2508144/how-to-convert-a-c-string-to-a-d-string

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