DATA Step, Macro, Functions and more

insert spaces between characters every third position

Accepted Solution Solved
Reply
New Contributor
Posts: 2
Accepted Solution

insert spaces between characters every third position

Hello all,

 

I've got a dataset (a) with the following characters:

211221222223215
133122111
822823
811811811823883884
215

 

I now want to create a space between after every third position. So the new dataset (b) would be like:

211 221 222 223 215
133 122 111
822 823
811 811 811 823 883 884
215

(the actual list is about 5000 observations)

 

I have tried the prxchange function and something with an array, but its not working.

 

Hopefully you have some ideas wich i can try?

Thanks in advance

 

 

 


Accepted Solutions
Solution
‎03-30-2018 07:22 AM
Super User
Posts: 10,569

Re: insert spaces between characters every third position

Posted in reply to Marcellllo

Use a do loop and substr():

data have;
input string :$30.;
cards;
211221222223215
133122111
822823
811811811823883884
215
;
run;

data want (rename=(newstring=string));
set have;
i = 1;
length newstring $30;
do until (i > length(string));
  newstring = catx(' ',newstring,substr(string,i,3));
  i + 3;
end;
drop i string;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code

View solution in original post


All Replies
Solution
‎03-30-2018 07:22 AM
Super User
Posts: 10,569

Re: insert spaces between characters every third position

Posted in reply to Marcellllo

Use a do loop and substr():

data have;
input string :$30.;
cards;
211221222223215
133122111
822823
811811811823883884
215
;
run;

data want (rename=(newstring=string));
set have;
i = 1;
length newstring $30;
do until (i > length(string));
  newstring = catx(' ',newstring,substr(string,i,3));
  i + 3;
end;
drop i string;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
New Contributor
Posts: 2

Re: insert spaces between characters every third position

Posted in reply to KurtBremser

It works

 

Thanks a lot!

Super User
Posts: 10,849

Re: insert spaces between characters every third position

Posted in reply to Marcellllo
data have;
input string :$30.;
want=prxchange('s/(\d\d\d)/$1 /',-1,string);
cards;
211221222223215
133122111
822823
811811811823883884
215
;
run;
proc print;run;
☑ This topic is solved.

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

Discussion stats
  • 3 replies
  • 121 views
  • 0 likes
  • 3 in conversation