Cover Image for Find Occurrence of Substring in C using Function
95 views

Find Occurrence of Substring in C using Function

To find the occurrences of a substring within a given string in C using a function, you can create a function that searches for the substring and counts how many times it appears. Here’s a simple C program that demonstrates this:

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

// Function to count occurrences of a substring in a string
int countSubstringOccurrences(const char *string, const char *substring) {
    int count = 0;
    int substringLength = strlen(substring);

    while (*string) {
        if (strncmp(string, substring, substringLength) == 0) {
            count++;
            string += substringLength - 1; // Move the pointer to the end of the matched substring
        }
        string++;
    }

    return count;
}

int main() {
    const char *text = "This is an example. Example is important. Another example.";
    const char *substring = "example";

    int occurrences = countSubstringOccurrences(text, substring);

    printf("Substring '%s' appears %d times in the text.\n", substring, occurrences);

    return 0;
}

In this program:

  • The countSubstringOccurrences function takes two arguments: the string in which to search for the substring and the substring to be found.
  • Inside the function, we use a while loop to iterate through the string. We use the strncmp function to compare a portion of the string with the substring. When a match is found, we increment the count and move the pointer to the end of the matched substring.
  • The count variable keeps track of how many times the substring appears in the string.
  • In the main function, we call countSubstringOccurrences to find the occurrences of the substring in the text and then print the result.

When you run this program, it will count and display the number of occurrences of the specified substring within the given text.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS