Count of substrings containing only the given character | Java program for the above approach ; Function that finds the count of substrings containing only character C in the string S ; To store total count of substrings ; To store count of consecutive C 's ; Loop through the string ; Increase the consecutive count of C 's ; Add count of sub - strings from consecutive strings ; Reset the consecutive count of C 's ; Add count of sub - strings from consecutive strings ; Print the count of sub - strings containing only C ; Driver Code
import java . util . * ; class GFG { static void countSubString ( String S , char C ) { int count = 0 ; int conCount = 0 ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { char ch = S . charAt ( i ) ; if ( ch == C ) conCount ++ ; else { count += ( conCount * ( conCount + 1 ) ) / 2 ; conCount = 0 ; } } count += ( conCount * ( conCount + 1 ) ) / 2 ; System . out . println ( count ) ; } public static void main ( String s [ ] ) { String S = " geeksforgeeks " ; char C = ' e ' ; countSubString ( S , C ) ; } }