Frequency of a substring in a string | Simple C ++ program to count occurrences of pat in txt . ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countFreq ( string & pat , string & txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int res = 0 ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { res ++ ; j = 0 ; } } return res ; } int main ( ) { string txt = " dhimanman " ; string pat = " man " ; cout << countFreq ( pat , txt ) ; return 0 ; }