to delete the '\0' characters

Salih Dincer salihdb at hotmail.com
Fri Sep 23 18:37:59 UTC 2022


On Friday, 23 September 2022 at 14:38:35 UTC, Jesse Phillips 
wrote:
> 
> You should be explicit with requirements.

Sorry, generally what I speak is Turkish language. So, I speak 
English as a foreign language but it's clear I wrote. What do you 
think when you look at the text I've pointed to following?

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?**

* character**S**
* at the **END**
* of the **STRING**

> ```d
> auto splitz(string s) {
>     return s.splitter('\0')
>    .filter!(x => !x.empty);
> }
> ```

By the way, if we're going to filter, why are we splitting? 
Anyways! For this implementation, indexOf() is a powerful enough 
tool. In fact, it's pretty fast, as there is a maximum of the \0 
8 characters possible and when those 8 '\0' are at the end of the 
string! For example:

```d
void main()
{
   string[] samples = ["the one\0", "the two\0\0", "the 
three\0\0\0",
                       "the four\0\0\0\0", "the five\0\0\0\0\0",
                       "the six\0\0\0\0\0\0", "the 
seven\0\0\0\0\0\0\0",
                       "the eight\0\0\0\0\0\0\0\0"];

   import std.stdio : writefln;
   foreach(s; samples)
   {
     auto start = s.length - 8;
     string res = s.splitZeros!false(start);
     writefln("%(%02X%)", cast(ubyte[])res);
   }
}

string splitZeros(bool keepSep)(string s, size_t start = 0)
{
   auto keep = keepSep ? 0 : 1;

   import std.string : indexOf;
   if(auto seekPos = s.indexOf('\0', start) + 1)
   {
     return s[0..seekPos - keep];
   }
   return s;
}
```
SDB at 79


More information about the Digitalmars-d-learn mailing list