March 17, 2005
<code>
   import std.stdio;
   int checkString( char[] s )
   {
       if ( s != "" )
           writef("\n  Your string is \"%s\"\n", s );
       else
           writef("\n  Your string is empty/not set!\n");
       return 0;
   }
   void main()
   {
       char[] a = "TEST string";
       char[] b;
       checkString(a);
       checkString(b);
   }
</code>

The above example works fine. I also tested

   if ( s )

that also worked. But what is the best way to check it a string is "set properly"?

In ANSI I used to do:

       if ( strlen(s) > 0 )

AEon
March 17, 2005
AEon wrote:

> But what is the best way to check it a string is "set properly"?

Check the value of s.ptr ... (if "s" is a string variable)


If s is null, it too will be null.

If s == "", it will point to a '\0' (i.e. not to null)


Note that any null "s" will also be == "", as per definition.
(and both of null and "" have a .length attribute of 0, too)

--anders
March 17, 2005
On Thu, 17 Mar 2005 17:20:02 +0100, Anders F Björklund wrote:

> AEon wrote:
> 
>> But what is the best way to check it a string is "set properly"?
> 
> Check the value of s.ptr ... (if "s" is a string variable)
> 
> 
> If s is null, it too will be null.
> 
> If s == "", it will point to a '\0' (i.e. not to null)
> 
> 
> Note that any null "s" will also be == "", as per definition. (and both of null and "" have a .length attribute of 0, too)

Except that in some circumstances, D makes no distinction between an empty string and an unassigned string. Sometimes, assigning "" to a string will cause the .ptr value to be set to zero. I just can't remember under what conditions this occurs, but it does happen.

-- 
Derek Parnell
Melbourne, Australia
18/03/2005 7:30:51 AM
March 18, 2005
[snip]
>  But what is the best way to check it a string is "set
> properly"?
>
> In ANSI I used to do:
>
>       if ( strlen(s) > 0 )

use
if (s.length > 0)
since it will work no matter what the ptr is.


March 19, 2005
On Fri, 18 Mar 2005 09:50:33 -0500, Ben Hinkle <bhinkle@mathworks.com> wrote:
> [snip]
>>  But what is the best way to check it a string is "set
>> properly"?
>>
>> In ANSI I used to do:
>>
>>       if ( strlen(s) > 0 )
>
> use
> if (s.length > 0)
> since it will work no matter what the ptr is.

Unless your aim is to tell empty and undefined apart, in which case...

char[] undefined;
char[] empty;

empty = "";

assert(undefined.length == 0);
assert(empty.length == 0);

assert(undefined is null);
assert(empty is null);  //this will assert

Regan
Top | Discussion index | About this forum | D home