text: Count of occurrences of a "1(0 + ) 1" pattern in a string | C # program to calculate number of times the pattern occurred in given string ; Returns count of occurrences of "1(0 + ) 1" int str . ; int count = 0 ; Initialize result ; Check if encountered '1' forms a valid pattern as specified ; if 1 encountered for first time set oneSeen to 1 ; Check if there is any other character other than '0' or '1' . If so then set oneSeen to 0 to search again for new pattern ; Driver Code
code: using System ; class GFG { public static int countPattern ( string str ) { int len = str . Length ; bool oneSeen = false ; for ( int i = 0 ; i < len ; i ++ ) { char getChar = str [ i ] ; if ( getChar == '1' && oneSeen == true ) { if ( str [ i - 1 ] == '0' ) { count ++ ; } } if ( getChar == '1' && oneSeen == false ) { oneSeen = true ; } if ( getChar != '0' && str [ i ] != '1' ) { oneSeen = false ; } } return count ; } public static void Main ( string [ ] args ) { string str = "100001abc101" ; Console . WriteLine ( countPattern ( str ) ) ; } }