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.
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.
What’s the difference between SAS Enterprise Guide and SAS Studio? How are they similar? Just ask SAS’ Danny Modlin.
Find more tutorials on the SAS Users YouTube channel.