Desktop productivity for business analysts and programmers

SAS string functions not returning expected result

Frequent Contributor
Posts: 82

SAS string functions not returning expected result

I have a string like this:

ABCD 0101  (only 1 space in middle)

I want ABCD_0101

I tried:

TRANWRD (trim("ABCD 0101")," ","_")

And also:

TRANSLATE (trim(("ABCD 0101"),"_"," ")

And the output is:ABCD0101 (both cases)

What did i do wrong?

Regular Contributor
Posts: 217

Re: SAS string functions not returning expected result


The to and from locations are not always the same in every function. The only difference I see in our code is the "trim" function and I placed my translate result into a new variable.

9445  data _null;
9446      RSK_SEG_ID = 'ABCD 0101';
9447   rsk_seg_id_trans = translate(rsk_seg_id,'_',' ');
9448   put rsk_seg_id = rsk_seg_id_trans=;
9449  run;

RSK_SEG_ID=ABCD 0101 rsk_seg_id_trans=ABCD_0101



9478 data _null;

9479 RSK_SEG_ID = ' ABCD 0101 ';

9480 rsk_seg_id_trans = translate(rsk_seg_id,'_',' ');

9481 rsk_seg_id_trans2 = translate(trim(left(rsk_seg_id)),'_',' ');

9482 rsk_seg_id_trans3 = translate(' ABCD 0101 ','_',' ');

9483 rsk_seg_id_trans4 = translate(trim(left(' ABCD 0101 ')),'_',' ');

9484 put rsk_seg_id = rsk_seg_id_trans= rsk_seg_id_trans2= rsk_seg_id_trans3= rsk_seg_id_trans4=;

9485 run;

RSK_SEG_ID=ABCD 0101 rsk_seg_id_trans=__ABCD_0101__ rsk_seg_id_trans2=ABCD_0101 rsk_seg_id_trans3=__ABCD_0101__


Message was edited by: James Willis. I added spaces before and after and I added the trim(left()) functions.

Posts: 1,146

Re: SAS string functions not returning expected result

The code you've posted has two parentheses after TRIM in the TRANSLATE example, which will result in a syntax error. It's very important to always check the log!

Other than that, your TRANSLATE example should work perfectly; in this use case, TRANSLATE is more appropriate than TRANWRD.

Here's the example that worked for me:

data have;

SourceString = "ABCD 0101";

TargetString = TRANSLATE (trim("ABCD 0101"),"_"," ");



Ask a Question
Discussion stats
  • 2 replies
  • 3 in conversation