/*

 * srch_str.c

 * This program reads two strings and finds all the occurrences of the second

 * string within the first.

 */

 

#include <stdio.h>

#include <string.h>

 

#define MAX_LENGTH 80

 

int main ()

{

  char   str1[MAX_LENGTH + 1];  /* The first string. */

  char   str2[MAX_LENGTH + 1];  /* The second string. */

  char   *p_suffix;             /* The current suffix of the first string. */

  char   *p_place;              /* The current occurence of the second string

                                   in this suffix. */

  int    index;                 /* The index in which it occurs. */

  int    n_occurs = 0;          /* Total number of occurences. */

 

  /* Read the input strings. */

  printf ("1. Please enter a string (at most %d characters): ", MAX_LENGTH);

  scanf ("%s", str1);

  printf ("2. Please enter a string (at most %d characters): ", MAX_LENGTH);

  scanf ("%s", str2);

 

  /* Initially, the suffix of str1 equals the entire string. */

  p_suffix = str1;

 

  while ((p_place = strstr (p_suffix, str2)) != NULL)

  {

    /* Print the current occurence. */

    index = p_place - str1;

    printf ("- Found \"%s\" at index %d.\n", str2, index);

 

    /* Take the suffix so it begins one character after the location of the

       current occurence of str2. */

    p_suffix = p_place + 1;

 

    /* Update the number of occurences. */

    n_occurs++;

  }

 

  printf ("Found %d occurence%s in total.\n",

          n_occurs, (n_occurs == 1) ? "" : "s");

 

  return (0);

}