Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D2: empty string in a conditional statement

Tags:

d

In the following code, why does 2 give output but not 3? The removechars statement returns a string with 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 may return null, but I'm still a bit puzzled because all of these print true

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

Edit 2: This also prints true, but put either of them in a conditional and you get a different result

writeln("" == null);

Edit 3: Alright, I understand that I cannot test for an empty string the way I did. What led to this question is the following situation. I want to remove chars from a word, but don't want to store an empty string:

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

This works when I try it, but that must be because removechars is returning null rather than ""

like image 836
fwend Avatar asked Dec 08 '25 20:12

fwend


1 Answers

Because removeChars will return null when no characters match.

(This happens because .dup of an empty string will always be null.)

like image 106
Vladimir Panteleev Avatar answered Dec 11 '25 12:12

Vladimir Panteleev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!