title: Counting substrings in C
body: <p>A friend of mine needed help counting the occurrences of a substring in a string, and I came up with the following code. Does anyone know a better method to do this?</p>
  
  <pre><code>#include "stdio.h"
  #include "string.h"
  
  int main(int argc, char *argv[])
  {
      char str1[50], str2[50];
      int i, j, l1, l2, match, count;
  
      printf("String 1:\n");
      gets(str2);
      printf("String 2:\n");
      gets(str1);
  
      l1 = strlen(str1);
      l2 = strlen(str2);
  
      count = 0;
  
      for(i = 0; i &lt; l1; i++)
      {
          match = 0;
          for(j = 0; j &lt; l2; j++)
          {
              if(str1[i + j] == str2[j])
              {
                  match++;
              }
          }
  
          if(match == l2)
          {
              count++;
          }
      }
  
      printf("Substrings: %d\n", count);
  }
  </code></pre>