Return to Archive

SAS Tip of the Month
September 2007

Since when does a null string have a length of 1?

This question is an interesting one and is solved by using the correct ‘length’ function. The SAS documentation as the following for the ‘length’ related functions:

LENGTH -- Returns the length of a non-blank character string, excluding trailing blanks, and returns 1 for a blank character string
LENGTHC -- Returns the length of a character string, including trailing blanks
LENGTHM -- Returns the amount of memory (in bytes) that is allocated for a character string
LENGTHN -- Returns the length of a non-blank character string, excluding trailing blanks, and returns 0 for a blank character string

So lets look at what each function brings up if we have a string with text and a second with nothing in it, noting that both are defined with a length of 30 characters:

   357 data _null_;
   358 length TextStr1 TextStr2 $30;
   359 TextStr1='32 Windsor Gardens, London';
   360 TextStr2=' ';
   361 LENGTH1=length(TextStr1);
   362 LENGTHC1=lengthc(TextStr1);
   363 LENGTHM1=lengthm(TextStr1);
   364 LENGTHN1=lengthn(TextStr1);
   365 LENGTH2=length(TextStr2);
   366 LENGTHC2=lengthc(TextStr2);
   367 LENGTHM2=lengthm(TextStr2);
   368 LENGTHN2=lengthn(TextStr2);
   369 put TextStr1= /
   370 LENGTH1= LENGTHC1= LENGTHM1= LENGTHN1= /
   371 TextStr2= /
   372 LENGTH2= LENGTHC2= LENGTHM2= LENGTHN2=;
   373 run;

   TextStr1=32 Windsor Gardens, London
   LENGTH1=26 LENGTHC1=30 LENGTHM1=30 LENGTHN1=26
   TextStr2=
   LENGTH2=1 LENGTHC2=30 LENGTHM2=30 LENGTHN2=0

It is interesting to note that the LENGTHN function actually got it right in both cases, particularly when you consider that the second string, variable TextStr2, was set to null.

________________________________
Updated September 1, 2007