University of Rochester Medical Center
SearchDirectoryNewsEventsStrong HealthURMC Home

SAS Helpful Hints

Biostat Macro Library

Parse a string word by word

Occasionally I like to read through a string, word by word. This macro makes it easy. It plucks off the first word from a character variable.

%Macro parse(string,word);
    sspace=Index(&string,' ');
    llen=Length(&string);
    If sspace>0 Then &word=Substr(&string,1,sspace); Else &word=' ';
    If llen-sspace>0 Then &string=Substr(&string,sspace+1,llen-sspace); Else &string=' ';
%Mend parse;

Data work.A;
    sentence='Have you seen the mouse?';
    word='Nothing';
    Do While (word^=' ');
        %parse(sentence,word);
        Put word= $ sentence= $;
    End;
Run;

The above procedure works well for character variables in a data step. To pluck the first word from a Macro variable, the syntax is a little different:

%Macro NextWord(string);
    %Let space=%Index(&&&string,%Str( ));
    %Let size=%Length(&&&string);
    %If %Eval(&space)>0 %Then %Do;
        %Let NextWord=%Substr(&&&string,1,&space);
        %Let &string=%Substr(&&&string,&space+1,&size-&space);
    %End; %Else %Do; %Let NextWord=&&&string; %Let &string= ; %End;
    &NextWord
%Mend NextWord;

%Let sentence=Where did the mouse go?;
%Macro test;
    %Let aword=%NextWord(sentence);
    %Do %While(%Length(&aword)>0);
        %Put Word=&aword Remaining sentence=&sentence;
        %Let aword=%NextWord(sentence);
    %End;
%Mend test;
%test;

Please send your comments and suggestions about this web page to A. Watts (watts@bst.rochester.edu)