print ubyte[] as (ascii) string

Steven Schveighoffer schveiguy at gmail.com
Fri Dec 31 14:45:41 UTC 2021


On Thursday, 30 December 2021 at 09:34:27 UTC, eugene wrote:
> I suspect the question was asked somewhere before.
> If so just give a link.
>
> Anyway:
>
> ```d
>
> class IoContext {
>     ...
>     ubyte[] buf;
>     ...
>     this(uint bufSize) {
>         buf = new ubyte[bufSize];
>     }
> }
>
> ```
>
> The buffer contains (ascii) string terminated with '\n'.
> In order to print it not as an array of numbers (buf is 1024 
> bytes long),
> but as usual string I do
>
> ```d
> char[] s = cast(char[])ioCtx.buf[0 .. 
> strlen(cast(char*)ioCtx.buf.ptr) - 1];
> // -1 is to eliminate terminating '\n'
> writefln("got '%s' from '%s:%d'", s, client.addr, client.port);
> ```
>
> Is there some more concise/elegant way to do that?
>
> Of course, I could use old good printf() instead:
> ```d
> printf(
>     "got '%s' from '%s:%d'\n",
>     ioCtx.buf.ptr,            // '\n' still there
>     toStringz(client.addr),
>     client.port
> );
> ```
>
> but I want to use D stdlib, not libc.

Unless I'm misunderstanding:

```d
import std.algorithm  : until;
writefln("got '%s' from '%s:%d'", 
(cast(char[])ioCtx.buf[]).until('\n'), client.addr, client.port);
```

Note that this does not save the "sliced" version of the buffer, 
so if you wanted to just search for the `\n` once, and keep using 
it, then you may want to use an algorithm that slices off 
everything until the character.

-Steve


More information about the Digitalmars-d-learn mailing list