Hi! I have a string something like this: "1234000111123012001210", i.e. it consists of random natural numbers between 0 and 9 and max lenght is 24. I need to find out how long the longest substring not containing 0 is. In this example the answer is 6 because the substring "111123" is the longest one not containing a 0. How can I do this? I was thinking of putting my string in an array and then loop thru it and count the characters until a 0 occurs, keep the value and compare it against the next substring not containing 0. My thoughts in code:
data a;
str='1234000111123012001210';
array b[24] $;
do i=1 to dim(b);
b[i]=substr(str,i,1);
end;
drop i;
count=0;/*the counter used to find the longest substring*/
do i=1 to dim(b);
if b[i]>0 then count=count+1; /*this should caputre 1234 and count=4*/
else /*keep the value 4 and do not count the preceding three 0*/
/*then go back to counting the substring '111123'.count=6. compare this count with count=4. keep count=6 */
end;
drop i;
run;
I am stuck and would appreciate it if anyone can provide me with some help.
data _null_;
str='1234000111123012001210';
do i=1 to countw(str,'0');
max=max(max,length(scan(str,i,'0')));
end;
putlog "max:" max;
run;
You need two count variables, one that you increment continuously, and one that holds the current maximum count.
Another totally different two-step approach would be to first generate a new observation for each substring. Then you could do a subsequent SQL using max(length()) construct.
data _null_;
str='1234000111123012001210';
do i=1 to countw(str,'0');
max=max(max,length(scan(str,i,'0')));
end;
putlog "max:" max;
run;
This was exactly what I needed! Thanks a lot!
Simply split the string by "0", and count length each time retaining a maximum:
data want (drop=i);
str="1234000111123012001210";
i=1;
max_len=0;
do while(scan(str,i,"0") ne "");
max_len=max(lengthn(scan(str,i,"0")),max_len);
i=i+1;
end;
run;
Please mark @Ksharp 's post as the answer.
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Check out this tutorial series to learn how to build your own steps in SAS Studio.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.