The following program finds all the occurrences of a word in a text string. We set the text string as an array of characters of fixed size (although we could, instead, use the operator ‘new’) and read it from the standard input using the function cin.get(). The memory allocation for the word entered in the command line and passed on as argument is done by the system before this program is called and we find the pointer to the string in argv[1]. For every starting position i in the array a, tries to associate the substring starting from this position with the p, checking character by character for equality. Each time we reach the end of p successfully, we display the starting position (i) of the word in the text on the screen.

Continue reading