data sorted_string;
length Str $50 ;
Str = "ASDFKBSDEFWKSR";
run;
Sorting last N letters in str variable
Here is an easy to follow approach
data want;
set sorted_string;
array a {100} $ _temporary_;
N = 5;
pos = max(1, length(str)-(N - 1));
sub = substrn(str, pos, N);
do i = 1 to length(sub);
a[i] = char(sub, i);
end;
call sortc(of a[*]);
substr(str, max(1, pos, N)) = cats(of a[*]);
run;
How long can str be and how large can N be?
HI PeterClemmensen,
suppose last 5 letters
Here is an easy to follow approach
data want;
set sorted_string;
array a {100} $ _temporary_;
N = 5;
pos = max(1, length(str)-(N - 1));
sub = substrn(str, pos, N);
do i = 1 to length(sub);
a[i] = char(sub, i);
end;
call sortc(of a[*]);
substr(str, max(1, pos, N)) = cats(of a[*]);
run;
Here's one way for N=5
data intermediate;
set sorted_string;
array letter $ letter1-letter5 _temporary_;
last5letters=substr(str,length(str)-4);
do i=1 to 5;
letter(i)=substr(last5letters,i,1);
end;
call sortc(of letter:);
last5letters_sorted=cats(of letter:);
sorted_string=cats(substr(str,1,length(str)-5),last5letters_sorted);
drop i;
run;
For general N, you could replace 5 with a macro variable.
Hi PaigeMiller
Thank you very much your solution
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!
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.
Ready to level-up your skills? Choose your own adventure.