Sub | Java implementation of the approach ; Function to return the count of sub - strings starting from startIndex that are also the prefixes of str ; Function to return the count of all possible sub - strings of str that are also the prefixes of str ; If current character is equal to the starting character of str ; Driver code ; Function Call
public class GFG { public static int subStringsStartingHere ( String str , int n , int startIndex ) { int count = 0 , i = startIndex + 1 ; while ( i <= n ) { if ( str . startsWith ( str . substring ( startIndex , i ) ) ) { count ++ ; } else break ; i ++ ; } return count ; } public static int countSubStrings ( String str , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == str . charAt ( 0 ) ) count += subStringsStartingHere ( str , n , i ) ; } return count ; } public static void main ( String [ ] args ) { String str = " ababc " ; int n = str . length ( ) ; System . out . println ( countSubStrings ( str , n ) ) ; } }