BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
ghosh
Barite | Level 11

I would like to convert a char variable (KID) consisting of one or two digits and sometimes a letter appended to it, into a 5 digit character string starting with the letter K followed by the existing variable with zeroes inserted in between (_ID).  Ideally I would like to use a user-defined format to do the conversion or perhaps a more efficient approach than what I currently have:

 

 

	Select;
		When (length(KID)=1) Pad='000';
		When (length(KID)=2) Pad='00';
		otherwise Pad='0';
	End;
		_ID = cats('K',Pad,KID);

Here are the Have (KIDS) and Want (_ID) variables:

 

 

KID _ID
1a K001a
1b K001b
2a K002a
2b K002b
3 K0003
4 K0004
5 K0005
6 K0006
7 K0007
8 K0008
9 K0009
10 K0010
11 K0011
11a K011a
11b K011b
12a K012a
12b K012b

 

Thanks!

1 ACCEPTED SOLUTION

Accepted Solutions
Tom
Super User Tom
Super User

You could use the REPEAT function.

length _id $5;
_id='K'||repeat('0',3-length(kid))||kid;

View solution in original post

3 REPLIES 3
Tom
Super User Tom
Super User

You could use the REPEAT function.

length _id $5;
_id='K'||repeat('0',3-length(kid))||kid;
ghosh
Barite | Level 11
Thanks Tom! Great solution, plus I can adapt it for longer strings.
Ksharp
Super User
data have;
input KID $ _ID $;
length temp $ 4;
temp=kid;
want=cats('K',translate(right(temp),'0',' '));
cards;
1a K001a
1b K001b
2a K002a
2b K002b
3 K0003
4 K0004
5 K0005
6 K0006
7 K0007
8 K0008
9 K0009
10 K0010
11 K0011
11a K011a
11b K011b
12a K012a
12b K012b
;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 3321 views
  • 2 likes
  • 3 in conversation