Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

Count Occurrences of a Substring in a String in C

$
0
0

Here we’ll see how to write C program to find out the number of occurrences of a substring in a string. C string library (<string.h>) provides a function (strstr()) to determine whether a sub-string is present in a string or not. But that does not count the number of occurrences. We can implement our own function for that with or without using strstr() function.

The Program

/*test.c*/

#include <stdio.h>
#include <string.h>

#define MAX_STRING_SIZE 1024

int substring_count(char* string, char* substring) {
  int i, j, l1, l2;
  int count = 0;
  int found = 0;

  l1 = strlen(string);
  l2 = strlen(substring);

  for(i = 0; i < l1 - l2; i++) {
    found = 1;
    for(j = 0; j < l2; j++) {
      if(string[i+j] != substring[j]) {
        found = 0;
        break;
      }
    }

    if(found) {
      count++;
      i = i + l2 -1;
    }
  }

  return count;
}

int main(){
  char string[MAX_STRING_SIZE];
  char substring[MAX_STRING_SIZE];
  int count = 0;

  printf("Enter a string: ");
  gets(string);

  printf("Enter a substring: ");
  gets(substring);

  count = substring_count(string, substring);

  printf("Substring occurrence count is: %d.\n", count);

  return 0;
}

This program takes two inputs, the string and the sub-string. The substring_count() function counts the number of occurrence of the sub-string. It iterates the string character by character and assumes that every character could be the beginning of the sub-string. It starts matching with the sub-string characters from there. If any mismatch is found (line 19), the inner loop breaks and the outer loop advances to the next character to repeat the same thing. If the all characters match in the inner loop, then match counter is incremented (line 26). The outer loop advanced by the length of the sub-string.

Here is the output.

Using strstr() Function

The substring_count() function is changed like this.

int substring_count(char* string, char* substring) {
  int i, j, l1, l2;
  int count = 0;

  l1 = strlen(string);
  l2 = strlen(substring);

  for(i = 0; i < l1 - l2; i++) {
    if(strstr(string + i, substring) == string + i) {
      count++;
      i = i + l2 -1;
    }
  }

  return count;
}

Instead of having our own inner loop to check whether the sub-string matches from a particular of the outer loop, we used the strstr() function. Function strstr() returns the pointer of starting character of the first match. If the pointer is equal to the pointer of starting character of the outer loop, we increment match counter.

We can achieve the same thing using strcmp() function also.

The post Count Occurrences of a Substring in a String in C appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>