- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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?
Accepted Solutions
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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;
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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!
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
string=trim(left(letter))||string;