Count substrings that starts with character X and ends with character Y | Java 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
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static 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 . charAt ( i ) == x ) count_x ++ ; if ( str . charAt ( i ) == y ) tot_count += count_x ; } return tot_count ; } public static void main ( String args [ ] ) { String str = " abbcaceghcak " ; int n = str . length ( ) ; char x = ' a ' , y = ' c ' ; System . out . print ( " Count ▁ = ▁ " + countSubstr ( str , n , x , y ) ) ; } }