tags:

views:

128

answers:

1

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 );
+8  A: 
  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).

CyberShadow
`toString` is deprecated in D2.
KennyTM
can't you do `string s = new string(c_str);` or my C++ knowledge faded drastically?
The Elite Gentleman
Question said D, not C++.
DK
@KennyTM, if toString is deprecated in D2, how should this be done when the length is unknown?
caspin
@Caspin: Use `to!string` or `text` from the `std.conv` module.
KennyTM
IIRC string is immutable so for case 2, you will need to throw in a cast (if you know the c-string is immutable or a `.idup` for other cases.
BCS
Sorry, I didn't notice that. I never knew there was a `D`. It looked just like C++.
The Elite Gentleman
@The Elite: Yup, it does and if you like C++, you should take a look at D. (Be warned the ecosystem is a bit immature at the moment).
BCS
OK, I'm already googling about `D`.
The Elite Gentleman
I feel like I'm the only person on Earth who still uses D1/Phobos :(
CyberShadow
@CyberShadow, D1 doesn't offer enough advantages over c++ to get my interest. D2's template syntax in particular is what has caught my interest, and range based containers instead of iterator based, and ...
caspin
Understandable, but be ready to rewrite your code with each D2 language change, which are still going to happen until the language stabilizes (which will happen when the D book is published). I have a sizable codebase of "serious" projects written in D to maintain, so using D2 would be reckless in my situation. (Which makes me think, are all D2 users simply not working on serious projects or just have too much time on their hands?)
CyberShadow