SAS 9.4M5
EG 7.14 x64
Data Step used for testing and debugging:
data _null_;
length szName $ 12;
szCourse = 'PHIL ';
szNmbr1 = '112 ';
szNmbr2 = '112LAB';
intLen = lengthn(cats(szCourse, szNmbr1));
intInsert = 11 - intLen;
szName = cat(trim(szCourse), repeat(' ', intInsert), trim(szNmbr1));
intNameLen = lengthn(szName);
intNameLen = length(szName);
intLen = lengthn(cats(szCourse, szNmbr2));
intInsert = 11 - intLen;
szName = cat(trim(szCourse), repeat(' ', intInsert), trim(szNmbr2));
intNameLen = lengthn(szName);
intNameLen = length(szName);
run;
The data step works as expected; it concatenates the course and number, separated by a derived number of spaces to produce a left-aligned course name, x spaces, right-aligned course number that is always 12 total character long. This comports with the SAS documentation for the repeat() function as an n+1 result.
When I move the core code into a proc FCMP function, repeat() behaves differently for some reason - it produces an n+2 result, requiring me to adjust my math.
PROC FCMP OUTLIB=&IE_Functions;
FUNCTION Build_Course_ID(szSubj $, szNumber $) $ 12;
length szName $ 12;
intInsert = 10 - lengthn(cats(szSubj, szNumber));
szName = cat(trim(szSubj), repeat(' ', intInsert), trim(szNumber));
return(szName);
ENDSUB;
RUN;
Works for me.
Careful how you manage the trailing spaces.
proc fcmp outlib=WORK.FUNCS.GEN;
function Build_Course_ID(STR1 $, STR2 $) $12 ;
LEN = 12 - length(cats(STR1, STR2));
OUT = catx(repeat(' ', LEN-1), STR1, STR2);
return( OUT );
endsub;
run;
options cmplib=WORK.FUNCS;
data t;
length A $12;
A=Build_Course_ID('xxxxx','yyyyy');
put A=;
run;
A=xxxxx yyyyy
Works for me.
Careful how you manage the trailing spaces.
proc fcmp outlib=WORK.FUNCS.GEN;
function Build_Course_ID(STR1 $, STR2 $) $12 ;
LEN = 12 - length(cats(STR1, STR2));
OUT = catx(repeat(' ', LEN-1), STR1, STR2);
return( OUT );
endsub;
run;
options cmplib=WORK.FUNCS;
data t;
length A $12;
A=Build_Course_ID('xxxxx','yyyyy');
put A=;
run;
A=xxxxx yyyyy
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and save with the early bird rate—just $795!
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.
Ready to level-up your skills? Choose your own adventure.