代码之家  ›  专栏  ›  技术社区  ›  deft_code

如何将C字符串转换为D字符串?

d
  •  11
  • deft_code  · 技术社区  · 16 年前

    这很简单,我不好意思问,但是如何在d2中将c字符串转换为d字符串呢?

    我有两个用例。

    string convert( const(char)* c_str );
    string convert( const(char)* c_str, size_t length );
    
    1 回复  |  直到 16 年前
        1
  •  16
  •   dsimcha    16 年前
    1. 使用std.string.tostring(char*)(d1/phobos)或std.conv.to!(字符串)(d2):

      // D1
      import std.string; 
      ... 
      string s = toString(c_str);
      
      // D2
      import std.conv;
      ...
      string s = to!(string)(c_str);
      
    2. 切片指针:

      string s = c_str[0..len];
      

      (不能使用“length”,因为它对slice语法有特殊意义)。

    两者都将返回C字符串上的切片(因此,引用而不是副本)。使用.dup属性创建副本。

    注意,D字符串被认为是UTF-8编码。如果字符串是另一种编码方式,则需要转换它(例如,使用std.windows.charset中的函数)。