Help using Base SAS procedures

Truncating a string into pieces?

Accepted Solution Solved
Reply
Super Contributor
Posts: 338
Accepted Solution

Truncating a string into pieces?

Hi SAS Forum,
I have a list of some 200 postal codes in the attached SAS data set as a string.

Q:

I need to get the postal codes separated. The final data set that I want should look like below.

postal_code

T1S0C3

T1S1A1

T1S1A2

T1S1A4

T1S1A5

.......

.......

.......

Could anyone help me to get the single string transformed into a data set like above?

Thank you for your time and expertise.

Mirisage

Attachment

Accepted Solutions
Solution
‎07-25-2013 10:11 AM
SAS Super FREQ
Posts: 683

Re: Truncating a string into pieces?

Have a look at this code

COUNTW will count the "words" delimited by a blank, SCAN will get the proper string

data postalcodes;
  postal_codes = "T1S0C3 T1S1A1 T1S1A2 T1S1A4 T1S1A5 T1S1A6 T1S1A7 T1S1A8 T1S1A9 T1S1B1 T1S1B2";
 
length postalCode $ 16;
  n_postalCodes = countw(postal_codes,
" ");
  do i = 1 to n_postalCodes;
    postalCode = scan(postal_codes, i, " ");
    output;
 
end;

 
drop postal_codes /* n_postalCodes i */;
run;
 

View solution in original post


All Replies
Respected Advisor
Posts: 3,124

Re: Truncating a string into pieces?

Please refer this thread for your answer:

https://communities.sas.com/thread/48092

Solution
‎07-25-2013 10:11 AM
SAS Super FREQ
Posts: 683

Re: Truncating a string into pieces?

Have a look at this code

COUNTW will count the "words" delimited by a blank, SCAN will get the proper string

data postalcodes;
  postal_codes = "T1S0C3 T1S1A1 T1S1A2 T1S1A4 T1S1A5 T1S1A6 T1S1A7 T1S1A8 T1S1A9 T1S1B1 T1S1B2";
 
length postalCode $ 16;
  n_postalCodes = countw(postal_codes,
" ");
  do i = 1 to n_postalCodes;
    postalCode = scan(postal_codes, i, " ");
    output;
 
end;

 
drop postal_codes /* n_postalCodes i */;
run;
 
Super Contributor
Posts: 338

Re: Truncating a string into pieces?

Hi Bruno

Thank you very much, your code worked nicely and explanation is very helpful.

Hi Hai.kuo,

Mnay thanks for your link which is very helpful.

Regards

Mirisage

☑ This topic is SOLVED.

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

Discussion stats
  • 3 replies
  • 263 views
  • 3 likes
  • 3 in conversation