将以零结尾的字符串转换为D字符串

3

Phobos中是否有将以零结尾的字符串转换为D字符串的函数?

到目前为止,我只找到了反向情况的toStringz

我需要在以下片段中使用此功能:

// Lookup user name from user id
passwd pw;
passwd* pw_ret;
immutable size_t bufsize = 16384;
char* buf = cast(char*)core.stdc.stdlib.malloc(bufsize);
getpwuid_r(stat.st_uid, &pw, buf, bufsize, &pw_ret);
if (pw_ret != null) {
    // TODO: The following loop maybe can be replace by some Phobos function?
    size_t n = 0;
    string name;
    while (pw.pw_name[n] != 0) {
        name ~= pw.pw_name[n];
        n++;
    }
    writeln(name);
}
core.stdc.stdlib.free(buf);

我使用它来通过用户ID查找用户名。

目前我假设UTF-8兼容性。

3个回答

6

有两种简单的方法可以实现:切片或使用std.conv.to函数:

const(char)* foo = c_function();
string s = to!string(foo); // done!

如果您暂时使用它或知道它不会被写入或在其他地方释放,您可以对其进行切片:

immutable(char)* foo = c_functon();
string s = foo[0 .. strlen(foo)]; // make sure foo doesn't get freed while you're still using it

如果您认为它可以被释放,您也可以通过切片然后复制来复制它:foo [0..strlen(foo)] .dup;

指针切片在所有数组情况下都是相同的,不仅仅是字符串:

int* foo = get_c_array(&c_array_length); // assume this returns the length in a param
int[] foo_a = foo[0 .. c_array_length]; // because you need length to slice

如果您需要字符串,请使用idup来创建不可变的副本。 - ratchet freak

2

只需切割原始字符串(不复制)。[] 中的 $ 被翻译为 str.length。如果零不在结尾,只需将 "$-1" 表达式替换为位置。

void main() {
    auto str = "abc\0";
    str.trimLastZero();
    write(str);
}

void trimLastZero (ref string str) { 
    if (str[$ - 1] == 0) 
        str = str[0 .. $ - 1];
}

2
你可以采取以下方法去除尾随的零并将其转换为字符串:
char[256] name;
getNameFromCFunction(name.ptr, 256);
string s = to!string(cast(char*)name);   //<-- this is the important bit

如果只传递name,那么它将转换为字符串,但是尾随的零仍然存在。因此,您需要将其转换为char指针,这样std.conv.to会在遇到'\0'之前将其转换为任何内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接