I saw. Thanks again!
To nail using SAS functions is a bit of a challenge until the pattern is absolute unlike a relatively cleaner PRX(Regular expression). So
data have;
input x_all :$20. expected ;
cards;
11110000011 4
111001111 9
111001111000 9
;
run;
data want;
set have;
want=ifn(0<count(substr(x_all,1,findc(x_all,'1','b')),'0')=2,
lengthn(substr(x_all,1,findc(x_all,'1','b'))),
max(0,findc(x_all,'0')-1));
run;
Seems to me this logic simplifies to finding the first 0.
If it's the first character you get a 0. If it's not the first 0, then you subtract 1 to find the position of the last 1 which is the sum of the values up to that point.
If you find no 0's, that means you have all ones, which is the length of the string.
data want;
set have;
x_total = findc(x_all, '0');
if x_total = 0 then x_total = length(x_all);
else if x_total > 0 then x_total - 1;
run;
Do you want to sum the digits or just count them?
You can use the VERIFY() function to find the first location that is not a '1'. Make sure to append something in case all of string is filled with ones. NOTE: Your first example as 7 ones, not six.
data test;
input str :$20. wrong right ;
want = verify(str||'0','1')-1 ;
cards;
1111111000000 6 6
0000001111111 7 0
1111000111111 10 4
;
Obs str wrong right want 1 1111111000000 6 6 7 2 0000001111111 7 0 0 3 1111000111111 10 4 4
Hi,
Just for fun:
data have;
input x_all :$20.;
cards;
1111111000000
0000001111111
1111000111111
;
run;
data want;
set have;
want = lengthn(prxchange('s/^(1*)(0*)(.*)/$1/', -1, x_all));
run;
Bart
...and one more:
data want1;
set have;
want = lengthn(scan(x_all,1,"0","M"));
run;
Bart
Thank you @yabwon for your time and contribution. Much appreciate it.
This one too perhaps?
want=max(0,findc(x_all,'0')-1);
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.