BookmarkSubscribeRSS Feed
keen_sas
Quartz | Level 8
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 .
3 REPLIES 3
SushilNayak
Obsidian | Level 7
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_;
sbb
Lapis Lazuli | Level 10 sbb
Lapis Lazuli | Level 10
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.
BPD
Obsidian | Level 7 BPD
Obsidian | Level 7
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
How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 9736 views
  • 0 likes
  • 4 in conversation