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 );
What Is stoi() in C++? In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings. The stoi() function is relatively new, as it was only added to the language as of its latest revision (C++11) in 2011.
A C-style string is simply an array of characters that uses a null terminator. A null terminator is a special character ('\0', ascii code 0) used to indicate the end of the string. More generically, A C-style string is called a null-terminated string.
This function is used to convert the numerical value to the wide string i.e. it parses a numerical value of datatypes (int, long long, float, double ) to a wide string. It returns a wide string of data type wstring representing the numerical value passed in the function.
Converting a std::string to a CString is as simple as: std::string stdstr("foo"); CString cstr(stdstr. c_str()); This works for both UNICODE and MBCS projects.
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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With