As an exercise, I am trying to disassemble a sting into individual characters, then reassemble the characters back to the original string into a new SAS dataset.
I can successfully disassemble the sting with this code:
data looky (drop=string);
input string $ 1-50;
do i=1 to length(string);
letter = substr(string, i, 1);
output;
end;
cards;
The quick brown fox jumped over the lazy dogs
;
run;
However, when I attempt to reassemble the string, the blanks are removed. I've tried using TRIM, STRIP, CAT, CATT and CATS and they all remove blanks:
data what;
length string $ 50;
retain string;
set work.looky;
string=strip(string)||letter;
run;
STRIP (and the other functions) returns Thequickbrownfoxjumpedoverthelazydogs
This simple put statement write the complete string to the log, blanks included:
data _null_;
set work.looky;
put @i letter @@; run;
The quick brown fox jumped over the lazy dogs
I am obviously misapplying the TRIM, STRIP CATT functions, but I am truly baffled as to what to use that will retain blanks. Simply using string||letter returns a completely blank column. What am I doing wrong?
Hello @MarkFisher,
@MarkFisher wrote:
letter = substr(string, i, 1);
You could turn around the above assignment statement to reassemble the characters:
data want; length string $ 50; retain string; set work.looky; substr(string, i, 1) = letter; run;
Hello @MarkFisher,
@MarkFisher wrote:
letter = substr(string, i, 1);
You could turn around the above assignment statement to reassemble the characters:
data want; length string $ 50; retain string; set work.looky; substr(string, i, 1) = letter; run;
SAS stores character variables as fixed length. So when you define STRING as length $50 it contains 50 spaces. When you set it to 'T' it now contains the letter T and 49 spaces.
You need to know where in those 50 characters you want to place the letter.
You could just write directly to the i'th position.
substr(string,i,1)=letter;
Or extract the first (i-1) values and append the new letter.
string=substrn(string,1,i-1)||letter;
Goodness, I didn't expect the solution to be so simple! I was obviously mis-applying the TRIM, STRIP and CAT functions.
Thank you all for your timely and thoughtful replies!
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.