
407 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
countSubstringOccurrencesfunction takes two arguments: thestringin which to search for thesubstringand thesubstringto be found. - Inside the function, we use a
whileloop to iterate through thestring. We use thestrncmpfunction to compare a portion of thestringwith thesubstring. When a match is found, we increment thecountand move the pointer to the end of the matched substring. - The
countvariable keeps track of how many times thesubstringappears in thestring. - In the
mainfunction, we callcountSubstringOccurrencesto find the occurrences of thesubstringin thetextand 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.