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;
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
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.