【问题标题】:How to cast a char* to string in D?如何将 char* 转换为 D 中的字符串?
【发布时间】:2012-02-07 08:50:18
【问题描述】:

我有一个标准的 char 指针,我试图将其转换为字符串。

// string to char*
char *x = cast(char*)("Hello World\0");

// char* to string?
string x = cast(string)x;
string x = cast(immutable(char)[])x;

错误!

任何想法如何将 char* 转换为 D 中的字符串?

【问题讨论】:

  • pst:字符串文字已经附加了\0
  • 如果通过胖指针已经知道长度,为什么会这样?为了 C 兼容性?
  • @Daevius,是的,这样当您调用 C 函数时,您不必用 toStringZ 包装所有字符串文字。

标签: string pointers casting char d


【解决方案1】:

使用std.conv.tochar* 转换为string。使用std.string.toStringZ 走另一条路。

import std.string;
import std.stdio;
import std.conv;

void main()
{
    immutable(char)* x = "Hello World".toStringz();
    auto s = to!string(x);
    writeln(s);
}

【讨论】:

    【解决方案2】:

    如果你知道确切的长度,你可以这样做:

    immutable(char)* cptr = obj.SomeSource();
    int len = obj.SomeLength();
    
    string str = cptr[0..len];
    

    对于某些情况(例如,如果字符串包含\0)是需要的。

    【讨论】:

    • 我认为len 的类型应该是size_t
    猜你喜欢
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多