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;
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.