# Find all the patterns of “1(0+)1” in a given string in C++

C++Server Side ProgrammingProgramming

Suppose a string has patterns like 1(0+)1. Where (0+) indicates non-empty consecutive occurrences of 1s. We have to find all of the patterns. The patterns can overlap. The string is not necessarily a binary string. It can hold digits and lowercase characters only. Suppose the string is like 1101001, then there are two such patterns. 101 and 1001.

To solve this problem, we will follow these steps −

• Iterate through all character c in the string

• When c is 1, then we iterate till the element is 0

• When the stream of 0 ends, we will check whether the next character is 1 or not

• These steps will be repeated until the end of string is reached.

## Example

#include<iostream>
using namespace std;
int countBinPattern(string main_str) {
char last_char = main_str[0];
int i = 1, counter = 0;
while (i < main_str.size()) {
if (main_str[i] == '0' && last_char == '1') {
while (main_str[i] == '0')
i++;
if (main_str[i] == '1')
counter++;
}
last_char = main_str[i];
i++;
}
return counter;
}
int main() {
string str = "10010110000101";
cout << "Number of substrings of pattern 1(0+)1 is: " << countBinPattern(str);
}

## Output

Number of substrings of pattern 1(0+)1 is: 4
Published on 01-Nov-2019 11:01:21