Search code examples
stringd

dlang how to convert and trim a char[] into a string?


I am trying to convert a buffer to string but apparently there is this space that I cannot remove
How should I strip this space and convert a char[] into an string container

string getClass(HWND hwnd=NULL){
    char[100] str;
    GetClassNameA(hwnd, str.ptr, str.length);
    writeln(str.dup.strip,'"'); //nothing is stripped, str is printed as 100 characters
    writeln(str[99]=='\0'); //false
    writeln(str[99]==' '); //false
    writeln(str.dup[99]=='\0'); //false
    writeln(str.dup[99]==' '); //false
    writeln(str.dup.strip[99]=='\0'); //false
    writeln(str.dup.strip[99]==' '); //false
    return to!string(str).strip; //same nothing is stripped
}

Solution

  • You need to slice the buffer with the correct length. GetClassName returns the length of the string so do something like

    char[100] buffer;
    auto recv = GetClassNameA(hwnd, buffer.ptr, buffer.length);
    if(recv == 0) throw new Exception("failed");
    char[] str = buffer[0 .. recv];
    // now you can work with str