to delete the '\0' characters

ag0aep6g anonymous at example.com
Thu Sep 22 11:14:58 UTC 2022


On 22.09.22 12:53, Salih Dincer wrote:
> Is there a more accurate way to delete the '\0' characters at the end of 
> the string? I tried functions in this module: 
> https://dlang.org/phobos/std_string.html
> 
> ```d
> auto foo(string s)
> {
>    string r;
>    foreach(c; s)
>    {
>      if(c > 0)
>      {
>        r ~= c;
>      }
>    }
>    return r;
> }
> ```

I don't understand what you mean by "more accurate".

Here's a snippet that's a bit shorter than yours and doesn't copy the data:

     while (s.length > 0 && s[$ - 1] == '\0')
     {
         s = s[0 .. $ - 1];
     }
     return s;

But do you really want to allow embedded '\0's? I.e., should 
foo("foo\0bar\0") really resolve to "foo\0bar" and not "foo"?

Usually, it's the first '\0' that signals the end of a string. In that 
case you better start the search at the front and stop at the first hit.


More information about the Digitalmars-d-learn mailing list