Just another variation:
data input;
input str $;
datalines;
A
A,B
A,B,C
A,B,C,D
;
run;
data want;
set input;
SubStrLength=findc(str, ',',-length(str)) ;
if SubStrLength=0 then WantStr=Str;
else WantStr=substr(str,1,SubStrLength-1);
drop SubStrLength;
run;
proc print;
run;
And this from @cidab:
data input; input str $; want = substr(str,1,length(str)-indexc(reverse(trim(str)),',')); ...
**trim the input string, reverse it and find the position of last (now first) comma, then substring input string from start to string length minus the number of characters to drop;
Just another variation:
data input;
input str $;
datalines;
A
A,B
A,B,C
A,B,C,D
;
run;
data want;
set input;
SubStrLength=findc(str, ',',-length(str)) ;
if SubStrLength=0 then WantStr=Str;
else WantStr=substr(str,1,SubStrLength-1);
drop SubStrLength;
run;
proc print;
run;
And this from @cidab:
data input; input str $; want = substr(str,1,length(str)-indexc(reverse(trim(str)),',')); ...
**trim the input string, reverse it and find the position of last (now first) comma, then substring input string from start to string length minus the number of characters to drop;
data input;
input str $;
want = substr(str,1,length(str)-indexc(reverse(trim(str)),','));
**trim the input string, reverse it and find the position of last (now first) comma, then substring input string from start to string length minus the number of characters to drop;
cidab has a great solution. I've used this a couple times now to only extract what I need from a string.
Nathan Och
data input_extract;
set input;
len = length(str);
do i =1 to len;
len1 = len -2;
sub_str = substr(str,1,len1);
end;
run;
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.