Obsidian | Level 7

## How many consecutive zeros in a variable

Hi,

I have a character variable called employment_flag of length 12 which either contains the values 1 or 0.

For example:

010000000010

011100100001

I want to find out the longest string of consecutive zeros between the first and last 1 for each value in this variable. For example, the answer for row 1 should be 8 and row 2 should be 4. Note that in example 2 we have a string of 2 zeros and 4 zeros but I'm interested in the longest string.

Any help is much appreciated!

Thanks

1 ACCEPTED SOLUTION

Accepted Solutions

## Re: How many consecutive zeros in a variable

Hi @zishaq,

Here's another (but very similar) suggestion in view of the condition "between the first and last 1":

``````data have;
input c \$12.;
cards;
010000000010
011100100001
;

data want;
set have;
do _n_=2 to countw(c,'1','m')-1;
m=max(m,lengthn(scan(c,_n_,'1','m')));
end;
run;``````

In case of less than two 1s in the string the above solution would (deliberately) return a missing value.

2 REPLIES 2
Super User

## Re: How many consecutive zeros in a variable

@zishaq wrote:

Hi,

I have a character variable called employment_flag of length 12 which either contains the values 1 or 0.

For example:

010000000010

011100100001

I want to find out the longest string of consecutive zeros between the first and last 1 for each value in this variable. For example, the answer for row 1 should be 8 and row 2 should be 4. Note that in example 2 we have a string of 2 zeros and 4 zeros but I'm interested in the longest string.

Any help is much appreciated!

Thanks

One way:

```data example;
input x :\$12.;
longest=0;
do i=1 to countw(x,'1');
longest = max(longest, length(scan(x,i,'1')));
end;
drop i;
datalines;
010000000010
011100100001
;```

The above code treats the 1 as delimiter for both the countw and scan functions to break the string up into "words" consisting of only 0 and uses the length function to return the number of characters.

## Re: How many consecutive zeros in a variable

Hi @zishaq,

Here's another (but very similar) suggestion in view of the condition "between the first and last 1":

``````data have;
input c \$12.;
cards;
010000000010
011100100001
;

data want;
set have;
do _n_=2 to countw(c,'1','m')-1;
m=max(m,lengthn(scan(c,_n_,'1','m')));
end;
run;``````

In case of less than two 1s in the string the above solution would (deliberately) return a missing value.

Discussion stats
• 2 replies
• 611 views
• 7 likes
• 3 in conversation