LISTSERV at the University of Georgia
Menubar Imagemap
Home Browse Manage Request Manuals Register
Previous messageNext messagePrevious in topicNext in topicPrevious by same authorNext by same authorPrevious page (September 1997, week 2)Back to main SAS-L pageJoin or leave SAS-L (or change settings)ReplyPost a new messageSearchProportional fontNon-proportional font
Date:         Tue, 9 Sep 1997 18:05:56 -0700
Reply-To:     PDORFMA@ucs.att.com
Sender:       "SAS(r) Discussion" <SAS-L@UGA.CC.UGA.EDU>
From:         Paul Dorfman <PDORFMA@UCS.ATT.COM>
Organization: AT&T Universal Card Services
Subject:      Function to count WORDS in SAS
Content-Type: text/plain; charset=us-ascii

Bruce Goodman <bgoodman@PROBE.NET> wrote:

>Quick question. Is there a function or macro which will >count the number of words in a string??? For example, SCAN(var,n) >will return me the n'th word, but is there a function that will >tell me how many words were actually found???

Bruce:

I do not recall having seen such a function per se, but there are a couple not too cumbersome ways around. A hammer sledge approach is obvious:

102 DATA _NULL_; 103 A = ' 356 OJ 096 SKD F08 256 '; 104 DO NW=1 TO LENGTH(A) UNTIL(SCAN(A,NW,' ')=' '); END; 105 NW+ -1; 106 PUT NW=; 107 RUN; NW=6 NOTE: The DATA statement used 0.02 CPU seconds and 4073K.

The observation that the number of words in a string is just the number of embedded blanks plus one leads to a far more elegant solution:

109 DATA _NULL_; 110 A = ' 356 OJ 096 SKD F08 256 '; 111 NW = LENGTH(LEFT(A))-LENGTH(COMPRESS(LEFT(A)))+1; 112 PUT NW=; 113 RUN; NW=6 NOTE: The DATA statement used 0.01 CPU seconds and 4073K.

But of course it's impossible to resist the temptation to put a little macro piece like

%MACRO NWORDS(S); LENGTH(LEFT(&S))-LENGTH(COMPRESS(LEFT(&S)))+1; %MEND NWORDS;

into an autocall library and to use it then as a 'real' user-defined function:

118 DATA _NULL_; 119 A = ' 356 OJ 096 SKD F08 256 '; 120 NW = %NWORDS(A); 121 PUT NW=; 122 RUN; NW=6 NOTE: The DATA statement used 0.02 CPU seconds and 4073K.

If, however, one experiences repugnance towards using the macro externally with relation to a data step, the macro definition can be inserted between the lines 118 and 119 which of course does not change a thing but creates an impression of having a user function defined directly in a data step.

Hope the above will make the process of word counting a little bit less laborious.

Paul M. Dorfman Decision Support Systems AT&T UCS Jax, Fl


Back to: Top of message | Previous page | Main SAS-L page