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 ""
Because removeChars will return null when no characters match.
(This happens because .dup of an empty string will always be null.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With