
164 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: thestring
in which to search for thesubstring
and thesubstring
to be found. - Inside the function, we use a
while
loop to iterate through thestring
. We use thestrncmp
function to compare a portion of thestring
with thesubstring
. When a match is found, we increment thecount
and move the pointer to the end of the matched substring. - The
count
variable keeps track of how many times thesubstring
appears in thestring
. - In the
main
function, we callcountSubstringOccurrences
to find the occurrences of thesubstring
in thetext
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.