data nnn;
set sashelp.class;
length rev_string $ 25;
do i=1 to length(rev_string);
rev_string=substr(Name,length(Name)-i,1);
end;drop i ;
proc print;run;
how reverse string (Name) where i did wrong in the class dataset
Is this an assignment? Otherwise, why not use the Reverse Function?
Yes Peter
I am trying instead of REVERSE function
@BrahmanandaRao wrote:
Yes Peter
I am trying instead of REVERSE function
Why write your own code instead of the REVERSE function?
The DO loop you wrote is incorrect. To reverse a string, you can use the SAS function REVERSE(). You can use it, like this:
rev_string = reverse(Name);
Your DO loop replaces REV_STRING with a single character each time through the loop ... not what is needed. Do you need help in fixing that?
What about blanks? For example, this code contains 7 trailing blanks in STRING:
length string $ 10;
string = 'ABC';
rev_string = reverse(string);
Using the REVERSE function, the result would contain 7 leading blanks followed by "CBA". Are you attempting to replicate that result, or are you intending to ignore the blanks and get "CBA" followed by 7 trailing blanks?
@Astounding wrote:
Your DO loop replaces REV_STRING with a single character each time through the loop ... not what is needed. Do you need help in fixing that?
What about blanks? For example, this code contains 7 trailing blanks in STRING:
length string $ 10; string = 'ABC'; rev_string = reverse(string);
Using the REVERSE function, the result would contain 7 leading blanks followed by "CBA". Are you attempting to replicate that result, or are you intending to ignore the blanks and get "CBA" followed by 7 trailing blanks?
Either of the "problems" caused by spaces in the REVERSE function are easy to fix. Easier than writing your own code.
Use two index variables: one to count down from length(name) to 1, the other starting at 1 and incrementing in the loop. Then use SUBSTR on the left and right side of the assignment (left for rev_string, right for name).
Also, an opportunity to use the rarely used character format $REVERS Format .
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
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.