Find all the patterns of "1(0 + ) 1" in a given string | SET 1 ( General Approach ) | Code to count 1 ( 0 + ) 1 patterns in a string ; Function to count patterns ; Variable to store the last character ; We found 0 and last character was '1' , state change ; After the stream of 0 ' s , ▁ we ▁ got ▁ a ▁ ' 1 ',  counter incremented ; Last character stored ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int patternCount ( string str ) { char last = str [ 0 ] ; int i = 1 , counter = 0 ; while ( i < str . size ( ) ) { if ( str [ i ] == '0' && last == '1' ) { while ( str [ i ] == '0' ) i ++ ; if ( str [ i ] == '1' ) counter ++ ; } last = str [ i ] ; i ++ ; } return counter ; } int main ( ) { string str = "1001ab010abc01001" ; cout << patternCount ( str ) << endl ; return 0 ; }