Extract First 5 Characters of String Variable with Varying Lengths

Accepted Solution Solved
Reply
New Contributor
Posts: 3
Accepted Solution

Extract First 5 Characters of String Variable with Varying Lengths

I have a zip code variable in a dataset that includes both 5- and 9-digit zip codes. I want all of them to be 5-digits but am having trouble extracting the first 5 digits of the variable. It is an extensive list, but some examples are 15009, 15208, 191451652, 193760024.

 

When I try to use substr,

 

data cases; set cases;

zip=substr(zip_char,1,5);

run;

 

it seems to truncate the zip codes that are already 5 characters long to "1". Any thoughts on how to avoid this?

 


Accepted Solutions
Solution
‎08-08-2017 11:45 AM
Super User
Posts: 5,511

Re: Extract First 5 Characters of String Variable with Varying Lengths

This would happen if ZIP_CHAR is not left-hand justified.  Luckily, it's easy to left-hand justify:

 

length zip $ 5;

zip = left(zip_char);

 

SUBSTR isn't really needed, once you have assigned a length to the new variable.

View solution in original post


All Replies
Super User
Posts: 5,431

Re: Extract First 5 Characters of String Variable with Varying Lengths

Perhaps your zip_char is right aligned.
Try to do left() prior to substr().
Data never sleeps
Solution
‎08-08-2017 11:45 AM
Super User
Posts: 5,511

Re: Extract First 5 Characters of String Variable with Varying Lengths

This would happen if ZIP_CHAR is not left-hand justified.  Luckily, it's easy to left-hand justify:

 

length zip $ 5;

zip = left(zip_char);

 

SUBSTR isn't really needed, once you have assigned a length to the new variable.

Super User
Posts: 7,809

Re: Extract First 5 Characters of String Variable with Varying Lengths

If zip_char has leading blanks this might be the cause. Use the strip() function to get rid of blanks before applying substr().

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
☑ This topic is solved.

Need further help from the community? Please ask a new question.

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