DATA Step, Macro, Functions and more

String to split into words using macro.

Reply
Contributor
Posts: 29

String to split into words using macro.

Hi,

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 .
Contributor
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( ));
%end;
%mend splitter;
%splitter(string=base macros sql advance)
%put _global_;
Super Contributor
Super Contributor
Posts: 3,174

Re: String to split into words using macro.

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;
%end;
%mend splitter;
%splitter(string=base\macros\sql\advance,wordpfx=xxx,dlm=\);


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

Re: String to split into words using macro.

Learner,

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';
i=1;
DO UNTIL(SCAN(string,i)='');
call symput('VAR'!!put(i,3. -L),SCAN(string,i));
i+1;
END;
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;
END;
RUN;

Regards,

BPD
Ask a Question
Discussion stats
  • 3 replies
  • 6552 views
  • 0 likes
  • 4 in conversation