text: Count substrings that starts with character X and ends with character Y | C ++ implementation to count substrings starting with character X and ending with character Y ; function to count substrings starting with character X and ending with character Y ; to store total count of required substrings ; to store count of character ' x ' up to the point the string ' str ' has been traversed so far ; traverse ' str ' form left to right ; if true , increment ' count _ x ' ; if true accumulate ' count _ x ' to ' tot _ count ' ; required count ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstr ( string str , int n , char x , char y ) { int tot_count = 0 ; int count_x = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == x ) count_x ++ ; if ( str [ i ] == y ) tot_count += count_x ; } return tot_count ; } int main ( ) { string str = " abbcaceghcak " ; int n = str . size ( ) ; char x = ' a ' , y = ' c ' ; cout << " Count ▁ = ▁ " << countSubstr ( str , n , x , y ) ; return 0 ; }