Tips:Counting Words in a List

From sasCommunity
Jump to: navigation, search

You can count the number of words in a list by using one of the counting functions: COUNT, COUNTC, COUNTW. Simple macros can be written to incorporate the functionality of these functions into the macro language. The following assume that the word delimiter is a blank, and both correctly allow for multiple blanks between words.

%macro countw(list=);
 %sysfunc(countw(&list))
%mend countw;

The %COUNT macro counts embedded blanks and adds one to the total.

%macro count(list=);
 %eval(%sysfunc(count(%cmpres(&list),%str( )))+1)
%mend count;

A list of typical Anchorage Zoo animals demonstrates the use of these macros.

%let critters = wolverines grizzlies   moose;
%put there are %countw(list=&critters) animals at the zoo;
%put there are %count(list=&critters) animals at the zoo;

Submitted by Art Carpenter. Contact me at my Discussion Page.

....see also