BookmarkSubscribeRSS Feed
Neeta
Fluorite | Level 6

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 🙂

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?

5 REPLIES 5
mohamed_zaki
Barite | Level 11

Chk this old thread

Reverse any string without using function

You do not need retain for that....

Astounding
PROC Star

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.
FreelanceReinh
Jade | Level 19

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);.

Reeza
Super User

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.  

 

PGStats
Opal | Level 21

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

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 5 replies
  • 1350 views
  • 1 like
  • 6 in conversation