D2: empty string in conditional expression

In the following code, why does 2 give output, but not 3? The removechars statement returns a string of length 0

import std.stdio, std.string;

void main() {
    string str = null;
    if (str) writeln(1); // no

    str = "";
    if (str) writeln(2); // yes

    if (",&%$".removechars(r"^a-z"))  writeln(3); // no
}

Edit: Ok, it might return null, but I'm still a bit puzzled because all of these prints are true

writeln(",&%$".removechars(r"^a-z") == "");
writeln(",&%$".removechars(r"^a-z") == null);
writeln(",&%$".removechars(r"^a-z").length == 0);

Edit 2: this also outputs true, but puts any of them in a conditional expression, and you get a different result

writeln("" == null);

Edit 3: Well, I understand that I cannot check for an empty string like I do. As a result of this, the following situation arose. I want to remove characters from a word, but do not want to store an empty string:

if (auto w = word.removechars(r"^a-z"))
    wordcount[w]++;

This works when I try to do this, but it should be because removechars returns null, not "

+3
source share
4 answers

removeChars null, .

( , .dup null.)

+5

D , , .

D NULL , , , assert ("" == null) assert ([] == null). if (str) , , null - . , .

, null: assert (str null). , bool, , .

+2

! () . , , length:

string str;
assert(str is null);    // str is null
assert(!str);           // str is null

str = "";
assert(str !is null);   // no longer null
assert(str);            // no longer null

assert(!str.length);    // but it zero length
+2
source
if(!str.length) { 
//dosomething ... 
}
0
source

All Articles