Count all substrings having character K | C # implementation of the approach ; Function to return the index of the next occurrence of character ch in str starting from the given index ; Return the index of the first occurrence of ch ; No occurrence found ; Function to return the count of all the substrings of str which contain the character ch at least one ; To store the count of valid substrings ; Index of the first occurrence of ch in str ; No occurrence of ch after index i in str ; Substrings starting at index i and ending at indices j , j + 1 , ... , n - 1 are all valid substring ; Driver code
using System ; class GFG { static int nextOccurrence ( String str , int n , int start , char ch ) { for ( int i = start ; i < n ; i ++ ) { if ( str [ i ] == ch ) return i ; } return - 1 ; } static int countSubStr ( String str , int n , char ch ) { int cnt = 0 ; int j = nextOccurrence ( str , n , 0 , ch ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( j != - 1 && j < i ) { j = nextOccurrence ( str , n , j + 1 , ch ) ; } if ( j == - 1 ) break ; cnt += ( n - j ) ; } return cnt ; } static public void Main ( ) { String str = " geeksforgeeks " ; int n = str . Length ; char ch = ' k ' ; Console . WriteLine ( countSubStr ( str , n , ch ) ) ; } }