print ubyte[] as (ascii) string

eugene dee0xeed at
Thu Dec 30 17:52:20 UTC 2021

On Thursday, 30 December 2021 at 17:43:14 UTC, Tejas wrote:
> I'm not at my computer anymore, could you please replace the 
> `0x00` with `0x0A` and tell me if `strip` still doesn't work 
> for my solution?


> I think the `fromstringz` is trimming the null bytes for you, 
> making the `\n` the last character, allowing `strip` to work.

Yes, you are right:

import std.stdio;
import std.string;

void main() {
     ubyte[8] b1 = [0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x0A, 0x00, 
     ubyte[8] b2 = [0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x0A, 0x0A, 
     /* "hello\n\0\0" */

     char[] s1 = fromStringz(cast(char*)b1.ptr);
     writefln("'%s, world'", s1.strip);

     char[] s2 = cast(char[])b2[0 .. $];
     writefln("'%s, world'", s2.strip);


mono:~/2-coding/d-lang/misc$ ./p
'hello, world'
'hello, world'

everything as needed.

More information about the Digitalmars-d-learn mailing list