Sample 26152: Retrieving the number of words in a macro variable
This sample uses a macro to count the number of words contained in a macro variable.
The macro is using a space as the delimiter.
Note: If you are counting the number of words in a non-macro variable, the COUNT, COUNTC or COUNTW functions can be used in a DATA step for SAS® 9 and later releases.
These sample files and code examples are provided by SAS Institute
Inc. "as is" without warranty of any kind, either express or implied, including
but not limited to the implied warranties of merchantability and fitness for a
particular purpose. Recipients acknowledge and agree that SAS Institute shall
not be liable for any damages whatsoever arising out of their use of this material.
In addition, SAS Institute will provide no support for the materials contained herein.
/* Method 1: WORD_COUNT1 */
/* This method is valid in SAS 9.1 and above. */
%let string = blue red green;
%let word_cnt=%sysfunc(countw(&string));
%put There are &word_cnt words in the string "&string";
/* Method 2: WORD_COUNT2 */
/* This method is valid in SAS 9.0 */
%let string=blue red green;
%let word_cnt=%eval(%sysfunc(count(%cmpres(&string),%str( )))+1);
%put There are &word_cnt words in the string "&string";
/* Method 3: WORD_COUNT3 */
/* This method works prior to SAS 9.0 */
%macro words(string);
%local count word;
%let count=1;
/* The third argument of the %QSCAN function specifies the delimiter */
%let word=%qscan(&string,&count,%str( ));
%do %while(&word ne);
%let count=%eval(&count+1);
%let word=%qscan(&string,&count,%str( ));
%end;
%eval(&count-1)
%mend words;
%let string=blue red green;
%put There are %words(&string) words in the string "&string";
These sample files and code examples are provided by SAS Institute
Inc. "as is" without warranty of any kind, either express or implied, including
but not limited to the implied warranties of merchantability and fitness for a
particular purpose. Recipients acknowledge and agree that SAS Institute shall
not be liable for any damages whatsoever arising out of their use of this material.
In addition, SAS Institute will provide no support for the materials contained herein.
The following is printed to the log:
There are 3 words in the string "blue red green"
Return the number of words contained in a macro variable.
Type: | Sample |
Topic: | SAS Reference ==> Macro
|
Date Modified: | 2009-06-12 10:50:42 |
Date Created: | 2007-08-23 15:11:47 |
Operating System and Release Information
SAS System | Base SAS | All | n/a | n/a |