Solved
Contributor
Posts: 21

# scan function

Dear All,

i new to sas. i am learning sas . i am exploring some sas functions.

i am testing scan function, it is not showing desired output.

data have;

chk="01 APR";

do i=1 to 3;

t=scan(chk,i,' ');

put t=;

g=length(t);

put g=;

if length(t) in (1 2) then d=t;

else if length(t)=3 then m=t;

else if length(t)=4 then y=t;

end;

put chk= d= m= y=;

run;

desired o/p;

chk=01 APR d=01 m=APR y=

but where as i got

chk=01 APR d=(missing) m=APR y=

it is getting puzzle to me , where i am going wrong

Thanks

Cathyn

Accepted Solutions
Solution
‎11-21-2014 07:22 PM
Super User
Posts: 8,127

## Re: scan function

Add some more PUT statements so you can see what is happening inside your do loop.

data have;

input chk \$20.;

put (_n_ chk) (=) ;

do i=1 to 3;

t=scan(chk,i,' ');

put i= t= @;

g=length(t);

put g= @;

if length(t) in (1 2) then d=t;

else if length(t)=3 then m=t;

else if length(t)=4 then y=t;

put (d m y) (=);

end;

put ;

cards;

01 APR

02 MAY 2014

run;

Perhaps you want to use the LENGTHN() function instead?

All Replies
Solution
‎11-21-2014 07:22 PM
Super User
Posts: 8,127

## Re: scan function

Add some more PUT statements so you can see what is happening inside your do loop.

data have;

input chk \$20.;

put (_n_ chk) (=) ;

do i=1 to 3;

t=scan(chk,i,' ');

put i= t= @;

g=length(t);

put g= @;

if length(t) in (1 2) then d=t;

else if length(t)=3 then m=t;

else if length(t)=4 then y=t;

put (d m y) (=);

end;

put ;

cards;

01 APR

02 MAY 2014

run;

Perhaps you want to use the LENGTHN() function instead?

Posts: 3,167

## Re: scan function

two fixes, for one reason. Since you are learning (well, who isn't on this forum), I will give you the opportunities to check out some Docs yourself before giving out explanations.

data have;

chk="01 APR";

do i=1 to 3;

t=scan(chk,i,' ');

put t=;

g=length(t);

put g=;

if lengthn(t) in (1,2)

/*if length(t) in (2) */

then d=t;

else if length(t)=3 then m=t;

else if length(t)=4 then y=t;

end;

put chk= d= m= y=;

run;

Posts: 1,147

## Re: scan function

Hi Cathyn,

To make it dynamic, i used the countw() which counts the number of words, separated by blank space. so once the count is available , we could use the same in do loop and can minimize the number of times the loop executes. This also corrects the problem you are facing. The use of lengthn function is also not required. Please try the below code,

data have;

chk="01 APR";

cnt=countw(chk);

do i=1 to cnt;

t=scan(chk,i,' ');

put t=;

g=length(t);

put g=;

if length(t) in (1 2) then d=t;

else if length(t)=3 then m=t;

else if length(t)=4 then y=t;

end;

put chk= d= m= y=;

run;

Thanks,

jag

Thanks,
Jag
Contributor
Posts: 21

## Re: scan function

TThank you all!!!!!

Before posting I used strip function to avoid trail blank. But doesn't work!!!

thank you Tom, hai.kuo and jag

cathy

🔒 This topic is solved and locked.