Does D have an equivalent to C#'s String.IsNullOrWhiteSpace?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Fri Oct 13 08:12:21 UTC 2017
On Friday, October 13, 2017 07:36:28 bauss via Digitalmars-d-learn wrote:
> On Thursday, 12 October 2017 at 18:17:54 UTC, Adam D. Ruppe wrote:
> > On Thursday, 12 October 2017 at 18:11:55 UTC, Nieto wrote:
> >> Does D have an equivalent to C#'s String.IsNullOrWhiteSpace()
> >> in the standard library?
> >
> > import std.string;
> >
> > if(str.strip().length == 0) {
> >
> > // is null, empty, or all whitespace
> >
> > }
>
> Or this:
> if(!str.strip()) {
> // is null, empty, or all whitespace
> }
Nope. That's wrong. You should basically never test a string (or any type of
dynamic array) with an if statement, loop condition, or assertion. It
doesn't check whether the array is empty. It checks whether it's null. So,
for instance, this code
-------------------------
import std.stdio;
import std.string;
void main()
{
string str1 = "hello";
writeln(isNullOrEmptyOrWS("hello"));
writeln(isNullOrEmptyOrWS(" "));
writeln(isNullOrEmptyOrWS(""));
writeln(isNullOrEmptyOrWS(null));
}
bool isNullOrEmptyOrWS(string str)
{
if(!str.strip())
return true;
return false;
}
-------------------------
prints out
false
false
false
true
whereas what you'd want is
false
true
true
true
Putting anything in an if condition is an implicit, explict cast to bool
(it's lowered to an explicit cast by the compiler, so its semantics are that
of an explicit cast, but it's implicit in that the compiler does it for
you).
if(cond)
is lowered to
if(cast(bool)cond)
and
if(!cond)
is lowered to
if(!cast(bool)cond)
and casting any dynamic array to a bool is equivalent to arr !is null. So,
if(!str.strip())
becomes
if(!cast(bool)(str.strip()))
which becomes
if(!(str.strip() is null))
which is the same as
if(str.strip() !is null)
whereas what you really want is
if(str.strip().empty)
or
if(str.strip().length != 0)
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list