String created from buffer has wrong length and strip() result is incorrect

Lucas Burson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Oct 16 23:29:23 PDT 2014


When creating a string from a ubyte[], I have an invalid length 
and string.strip() doesn't strip off all whitespace. I'm new to 
the language. Is this a compiler issue?


import std.string : strip;
import std.stdio  : writefln;

int main()
{
    const string ATA_STR = " ATA ";

    // this works fine
    {
       ubyte[] buffer = [' ', 'A', 'T', 'A', ' ' ];
       string test = strip(cast(string)(buffer));
       assert(test == strip(ATA_STR));
    }

    // This is where things breaks
    {
       ubyte[] buff = new ubyte[16];
       buff[0..ATA_STR.length] = cast(ubyte[])(ATA_STR);

       // read the string back from the buffer, stripping 
whitespace
       string stringFromBuffer = strip(cast(string)(buff[0..16]));
       // this shows strip() doesn't remove all whitespace
       writefln("StrFromBuff is '%s'; length %d", 
stringFromBuffer, stringFromBuffer.length);

       // !! FAILS. stringFromBuffer is length 15, not 3.
       assert(stringFromBuffer.length == strip(ATA_STR).length);

    }

    return 0;
}


More information about the Digitalmars-d-learn mailing list