DATA Step, Macro, Functions and more

String to split into words using macro.

Posts: 30

String to split into words using macro.


Can any one help me in solving this.

I have a string which consists of 4 words.I have to create macro to split the string into 4 words to create each word into a global macro variable and the same to be displayed as individual macro variable.

For ex. string=base macros sql advance.
i want each word to be an individual global macro variable like
word1=base word2=macros word3=sql etc.
and the same to be displayed as variable=value in log window.

How do u write a macro for this and to be displayed .
Posts: 31

Re: String to split into words using macro.

Hey Learner,
The macro is very simple. You just need to understand how the word breaking be done to assign that word to some variable.

Here is the code ::

%macro splitter(string=);
%let cnt=1;
%let num1=%scan(&string,&cnt,%str( ));
%do %while(&num1 ne %str( ));
%global word&cnt;
%let word&cnt=&num1;
%let cnt=%eval(&cnt+1);
%let num1=%scan(&string,&cnt,%str( ));
%mend splitter;
%splitter(string=base macros sql advance)
%put _global_;
Super Contributor
Super Contributor
Posts: 3,176

Re: String to split into words using macro.

Posted in reply to SushilNayak
Minor embellishment to code from Sushil Nayak taking advantage of COUNTW function (new with SAS 9), and to echo resolved macro var string back to the SASLOG -- also added optional macro invocation parameters for flexibility:

%macro splitter(string=,wordpfx=WORD,dlm=%str( ));
%do cnt=1 %to %sysfunc(countw(&string,&dlm));
%global &wordpfx&cnt;
%let &wordpfx&cnt = %scan(&string,&cnt,%str(&dlm));
%* echo macro var result to log window;
%put &wordpfx&cnt=&&&wordpfx&cnt;
%mend splitter;

Scott Barry
SBBWorks, Inc.
Occasional Contributor BPD
Occasional Contributor
Posts: 12

Re: String to split into words using macro.


Just in case you'd prefer not to leave SAS base you could use the following. It generates the macro variables and displays their values in the log. I haven't fully tested it but it should be good for any number of words in the string. Of course you can replace the TRIM/LEFT functions with the appropriate version 9 function.

data a;
string = 'base macros sql advance';
DO UNTIL(SCAN(string,i)='');
call symput('VAR'!!put(i,3. -L),SCAN(string,i));
DO j = 1 to (i-1);
x = symget('var'!!put(j,3.-l));
putv = 'var'!!TRIM(put(j,3.-l))!!'='!!TRIM(LEFT(x));
put putv;


Ask a Question
Discussion stats
  • 3 replies
  • 4 in conversation