home *** CD-ROM | disk | FTP | other *** search
/ Power CD-ROM!! 7 / POWERCD7.ISO / prgmming / clipper / strcount.c < prev    next >
C/C++ Source or Header  |  1993-10-14  |  2KB  |  88 lines

  1. /*
  2.  * GT CLIPPER STANDARD HEADER
  3.  *
  4.  * File......: strcount.c
  5.  * Author....: Andy M Leighton
  6.  * BBS.......: The Dark Knight Returns
  7.  * Net/Node..: 050/069
  8.  * User Name.: Andy Leighton
  9.  * Date......: 23/05/93
  10.  * Revision..: 1.00
  11.  *
  12.  * This is an original work by Andy Leighton and is placed in the
  13.  * public domain.
  14.  *
  15.  * Modification history:
  16.  * ---------------------
  17.  *
  18.  * $Log$
  19.  *
  20.  */
  21.  
  22. /*
  23.  *  $DOC$
  24.  *  $FUNCNAME$
  25.  *      GT_STRCOUNT()
  26.  *  $CATEGORY$
  27.  *      String
  28.  *  $ONELINER$
  29.  *      Count the number of times a substring appears in a string
  30.  *  $SYNTAX$
  31.  *      GT_StrCount(<cChrs>, <cStr>) --> nFreq
  32.  *  $ARGUMENTS$
  33.  *      <cChrs> - The substring to find the frequence of
  34.  *      <cStr>  - The string in which to find the character
  35.  *  $RETURNS$
  36.  *      nFreq   - The number of times <cChrs> occurs in <cStr>
  37.  *  $DESCRIPTION$
  38.  *      GT_StrCount() counts how many times a specified substring
  39.  *      appears in a string.
  40.  *      If the substring does NOT appear in <cStr> this function
  41.  *      will return 0.
  42.  *      If the substring is a single character use GT_ChrCount() as
  43.  *      it will be faster.
  44.  *
  45.  *      NOTE:
  46.  *         invalid parameters will return -1
  47.  *  $EXAMPLES$
  48.  *
  49.  *      ? GT_StrCount("the", "the cat sat on the mat")      // prints 2
  50.  *
  51.  *  $END$
  52.  */
  53.  
  54. #include "extend.h"
  55.  
  56. CLIPPER
  57. gt_strcount()
  58. {
  59.   char *s1, *s2;
  60.   int count, p1, p2, l1, l2;
  61.   int match = 1;
  62.  
  63.   if (ISCHAR(1) && ISCHAR(2)) {
  64.     s1  = _parc(1);
  65.     s2  = _parc(2);
  66.     l1  = _parclen(1);
  67.     l2  = _parclen(2);
  68.  
  69.     /* loop through s2 matching passed character (s1) with
  70.        each character of s1 */
  71.  
  72.     for (count = 0, p2 = 0; p2 <= (l2 - l1); p2++) {
  73.       match = 1;
  74.  
  75.       for (p1 = 0; p1 < l1; p1++) {
  76.         if (s1[p1] != s2[p2 + p1])
  77.           match = 0;
  78.       }
  79.       if (match)
  80.         count++;
  81.     }
  82.  
  83.     _retni(count);                  // return result
  84.   } else {
  85.     _retni(-1);                     // parameter mismatch - error -1
  86.   }
  87. }
  88.