Hi Everyone,
I want to find the position of the last "-" in the string below
123-56-8-101212
so that last "-" is in position 9.
Can anyone please help?
Thank you,
HC
KEY IS: reverse vs regular.
pos=index(reverse(lcat),'-'); give the position of the last '-' using the length of the whole VARIABLE (specified in datastep, format...)
pos1=findc(Lcat,'-','b');give the position of the last '-' using the length of the whole STRING
DATA test;
INFILE DATALINES DELIMITER=',' DSD;
INPUT status & $100.;
DATALINES;
"No aproved by Tong"
"No Approval by Paul"
"No Approval by Ryan"
"No approval by Amy"
;
RUN;
data test1; set test;
length=length(Status);
findc=findw(status,'by');
supervisor=substr(status,findc+2);run;
Cramming it all into one statement ....
data want;
set have;
last_dash = length(string) - length(scan(string, -1, '-') );
run;
Here's one approach:
data _null_;
string='123-56-8-101212';
pos=length(string)-index(reverse(string),'-')+1;
put pos=;
run;
I think this example work only when there the length of string is fix.
In a datafile, the Length(project) change while the index(reverse(project),'-') count from the end of the whole variable itself, so it is not working.
I need to change to
pos=100-index(reverse(project),'-')+1; 100 is the length of the variable.
I wonder if there is any better way.
Thank you,
HC
DATA test;
INFILE DATALINES DELIMITER=',' DSD;
INPUT project & $100.;
DATALINES;
"General DYn - CKXy:GD-CQASUB56209-2A10-520"
"General Dyn - Technology:XP-CQA6521-5A10-520"
;
RUN;
data test;
set test;
length=length(project);
last=index(reverse(project),'-');
pos=length(project)-index(reverse(project),'-')+1;
var=(substr(project,pos,5));
run;
Trim it after reversing it. Otherwise you add leading blanks.
SCAN() allows you to use negative indexes, ie searching backwards which would be a much simpler approach and a single function.
Cramming it all into one statement ....
data want;
set have;
last_dash = length(string) - length(scan(string, -1, '-') );
run;
data _null_;
string='123-56-8-101212';
pos=findc(string,'-','b');
put pos=;
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.