2013-10-08 104 views
3

Phobos中是否有將零終止字符串轉換爲D字符串的函數?將零終止字符串轉換爲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兼容性。

回答

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(富)] 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 
+0

如果你想要一個字符串,然後使用idup創建一個不可變的重複 –

2

只是片原始的字符串(不應對)。 $ inside []被轉換爲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你將其轉換爲字符串,但尾隨零會仍然在那裏。所以你把它轉換成一個字符指針,並且它將會轉換它遇到的任何東西,直到遇到一個'\0'