print ubyte[] as (ascii) string

Paul Backus snarwin at gmail.com
Sun Jan 2 15:13:06 UTC 2022


On Sunday, 2 January 2022 at 09:15:32 UTC, eugene wrote:
>
> ```
> p1.d(9): Error: cannot cast expression `until(b[], '\x0a', 
> Flag.yes)` of type `Until!("a == b", ubyte[], char)` to `char[]`
>
> ```

Here's a working version:

```d
import std.stdio;
import std.string;
import std.algorithm : until, map;
import std.conv : to;

void main() {
     ubyte[8] b = [0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x0A, 0x00, 0x00];
     /* "hello\n\0\0" */
     writefln("'%-(%s%), world'", b[].until('\n').map!(to!char));
}
```

This code uses `map!(to!char)` to convert the elements of the 
range from `ubyte` to `char`, then uses a `%-(...%)` format 
specifier to print out each element of the range using the format 
string inside the parentheses (in this case, `%s`).


More information about the Digitalmars-d-learn mailing list