www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Testing for empty/indefinded Stings?

reply AEon <AEon_member pathlink.com> writes:
<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
Mar 17 2005
next sibling parent reply =?ISO-8859-1?Q?Anders_F_Bj=F6rklund?= <afb algonet.se> writes:
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
Mar 17 2005
parent Derek Parnell <derek psych.ward> writes:
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
Mar 17 2005
prev sibling parent reply "Ben Hinkle" <bhinkle mathworks.com> writes:
[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.
Mar 18 2005
parent "Regan Heath" <regan netwin.co.nz> writes:
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
Mar 18 2005