DATA Step, Macro, Functions and more

Reversing string

Reply
Occasional Contributor
Posts: 16

Reversing string

Hi,

I'm a SAS newbie. I was trying out something to reverse the string. I know there is SAS function REVERSE but I want to write my own code for fun Smiley Happy

here is my code

 

 

data try;
name="Bellevue";
length revname $ 20;
retain revname;
do i= length(name) to 1 by -1;
revname=catx(revname, strip(substr(name, i, 1)));
output;
end;

run;

 

but if you run the code, I'm not getting string though I've used retain statement. Whats going wrong?

Super Contributor
Posts: 490

Re: Reversing string

[ Edited ]

Chk this old thread

Reverse any string without using function

You do not need retain for that....

Super User
Posts: 5,496

Re: Reversing string

Several items to note:

 

  1. As was already mentioned, you don't need RETAIN at all.
  2. OUTPUT should also be removed.  Using it creates multiple observations from the original single observation.
  3. CATX is the wrong function.  It looks like it should be CATS instead.
  4. Your original value for NAME does not contain any trailing blanks.  This becomes a much trickier problem if trailing blanks are involved.
  5. The STRIP function isn't doing anything and therefore should be removed.
Trusted Advisor
Posts: 1,117

Re: Reversing string

Posted in reply to Astounding

Good points from @Astounding. Regarding trailing blanks, I don't think they would be desired as leading blanks in variable REVNAME (and they wouldn't occur as such with the current approach). But if they were desired, one could create them easily with a final revname=right(revname);.

Super User
Posts: 19,769

Re: Reversing string

Retain is for keeping values as you move down a column or through the data set. Since you're not stepping through a traditional data set and operating on the same line the Retain function isn't required.  

 

Respected Advisor
Posts: 4,919

Re: Reversing string

Here is another approach, using a temporary array

 

data try;
length name revname $ 20;
array c{100} $1 _temporary_;
do name = "Bellevue", "stressed";
    call missing(of c{*});
    do i= 1 to length(name);
        c{dim(c)-i+1} = char(name,i);
        end;
    revname=cats(of c{*});
    output;
    end;
drop i;
run;

proc print noobs data=try; run;
PG
Ask a Question
Discussion stats
  • 5 replies
  • 365 views
  • 1 like
  • 6 in conversation