to delete the '\0' characters

Quirin Schroll qs.il.paperinik at gmail.com
Fri Sep 23 08:52:45 UTC 2022


On Thursday, 22 September 2022 at 10:53:32 UTC, Salih Dincer 
wrote:
> Is there a more accurate way to delete the '\0' characters at 
> the end of the string?

Accurate? No. Your code works. Correct is correct, no matter 
efficiency or style.

> I tried functions in this module: 
> https://dlang.org/phobos/std_string.html
>
> [code]

You won’t do it any shorter than this if returning a range of 
`dchar` is fine:
```d
auto removez(const(char)[] string, char ch = '\0')
{
     import std.algorithm.iteration;
     return string.splitter(ch).joiner;
}
```
If `dchar` is a problem and a range is not what you want,
```d
inout(char)[] removez(inout(char)[] chars) @safe pure nothrow
{
     import std.array, std.algorithm.iteration;
     auto data = cast(const(ubyte)[])chars;
     auto result = data.splitter(0).joiner.array;
     return (() inout @trusted => cast(inout(char)[])result)();
}
```
Bonus: Works with any kind of array of qualified char. As 
`string` is simply `immutable(char)[]`, `removez` returns a 
`string` given a `string`, but returns a `char[]` given a 
`char[]`, etc.

Warning: I do not know if the `@trusted` expression is really 
okay. The cast is not `@safe` because of type qualifiers: If 
`inout` becomes nothing (i.e. mutable), the cast removes `const`. 
I suspect that it is still okay because the result of `array` is 
unique. Maybe others know better?


More information about the Digitalmars-d-learn mailing list