Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a c string to a d string?

Tags:

d

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 );
like image 297
deft_code Avatar asked Mar 24 '10 13:03

deft_code


People also ask

Can we use stoi in C?

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.

What is the C-style character string?

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.

What is a Wstring C++?

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.

How do you convert std::string to CString?

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.


1 Answers

  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).

like image 108
Vladimir Panteleev Avatar answered Jan 07 '23 02:01

Vladimir Panteleev