SAS Programming

DATA Step, Macro, Functions and more
BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
pavank
Quartz | Level 8
data sorted_string;
    length Str $50 ;
    Str = "ASDFKBSDEFWKSR";
run;

Sorting last N letters in str  variable

1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20

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;

View solution in original post

5 REPLIES 5
PeterClemmensen
Tourmaline | Level 20

How long can str be and how large can N be?

pavank
Quartz | Level 8

 

HI PeterClemmensen,

suppose last 5 letters 

PeterClemmensen
Tourmaline | Level 20

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;
PaigeMiller
Diamond | Level 26

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.

--
Paige Miller
pavank
Quartz | Level 8

Hi PaigeMiller 

Thank you very much your solution

sas-innovate-white.png

Register Today!

Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9.

 

Early bird rate extended! Save $200 when you sign up by March 31.

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
  • 5 replies
  • 589 views
  • 1 like
  • 3 in conversation