如何将c字符串转换为d字符串? [英] how to convert a c string to a d string?
问题描述
这很简单,我很尴尬地问,但是如何在D2中将c字符串转换为d字符串?
This is so simple I'm embarrassed to ask, but how do you convert a c string to a d string in D2?
我有两个用例.
string convert( const(char)* c_str );
string convert( const(char)* c_str, size_t length );
推荐答案
-
使用std.string.toString(char *)(D1/Phobos)或std.conv.to!(string)(D2):
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];
(您不能使用"length",因为它在slice语法中具有特殊含义).
(you can't use "length" because it has a special meaning with the slice syntax).
两者都将在C字符串上返回一个切片(因此,是引用而不是副本).使用.dup属性创建副本.
Both will return a slice over the C string (thus, a reference and not a copy). Use the .dup property to create a copy.
请注意,D字符串被视为采用UTF-8编码.如果您的字符串采用其他编码,则需要对其进行转换(例如,使用std.windows.charset中的函数).
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).
这篇关于如何将c字符串转换为d字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!