In SAS 9.2
Is there a simple way to split a string?
%Let baseString = D1 D2 D3;
For I = 0 to end;
Output D1 the first time;
Output D2 the second time;
Output D3 the third time;
End loop;
I do not want to do this in a data step.
SCAN() or %SCAN()
data _null_;
basestring='D1 D2 D3';
do i=1 to countw(basestring);
word = scan(basestring,i);
put i= word=;
end;
run;
or
%do i=1 %to %sysfunc(countw(&basestring));
%let word = %scan(&basestring,&i);
%put i=&i word=&word;
%end;
SCAN() or %SCAN()
data _null_;
basestring='D1 D2 D3';
do i=1 to countw(basestring);
word = scan(basestring,i);
put i= word=;
end;
run;
or
%do i=1 %to %sysfunc(countw(&basestring));
%let word = %scan(&basestring,&i);
%put i=&i word=&word;
%end;
Here is a macro that I use that also puts everything you might need into macro variables. (I have just improved it a bit by stealing Tom's idea of using countw).
%MACRO makelist(base,list);
* create a set of macro variables named base1, base2 ... with values from list + list returned as <base>list;
%PUT &base &list;
%GLOBAL n&base &base.list;
%LET &base.list =&list;
%LET n&base=%sysfunc(countw(&list));
%DO i=1 %TO &&n&base;
%GLOBAL &&base&&n&base;
%LET &&base&&n&base=%SCAN(&list,&&n&base);
%END ; ;
%PUT n&base = &&n&base;
%DO i=1 %TO &&n&base; %PUT &base&i &&&base&i; %END;
%MEND;
%makelist(test,D1 D2 D3);
Then you can reference them with a loop in a macro eg. ...
PROC MEANS;
VAR &testlist; * D1 D2 D3;
OUTPUT OUT=testmeans MEAN=%DO I=1 %TO &ntest; &&test&i..m %END; ;
The output dataset contains means in the variables D1m D2m and D3m.
A reference that might help:
data _null_;
degStudLevComma = "aa,b,a";
total = countc(°StudLevComma, ',');
put "&total";
run;
In order to know when to end going through my string I need to use countc. My string is delimited by commas. When I do this I receive an error that I have too many arguments. I’m guessing this is because my variable has commas in it that are acting like variable separators.
You want the countW() function to see how many items are in your list. You can included commas if they are properly quoted.
This worked.
data _null_;
degStudLevComma = "D1,D2";
total = countw(degStudLevComma, ',');
put total;
run;
or
%macro testMacro();
%let degStudLevComma = "D1,D2";
%let total = %sysfunc(countw(°StudLevComma, ','));
%put total &total;
%mend;
%testMacro();
Example with embedded commas.
%let x=This,list,has,"5, not 6 or 7,",words;
%let n=%sysfunc(countw(%superq(x),%str(,),qm));
%put &=n;
N=5
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9.
Early bird rate extended! Save $200 when you sign up by March 31.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.