Complementary task for topic: 7
M Nemeth · 2023-08-29 15:21:04.624218'
DStrings: Count Occurrences of a Substring
DStrings: Count Occurrences of a Substring
Create a C program that reads a main string and a substring from the user. The program should then find and count the occurrences of the substring within the main string using a function that takes dynamic strings as arguments.
Hint: Use dynamic memory allocation to create the main string and the substring.
Prompt the user to enter the main string and the substring.
Pass the main string and the substring to a function to find and count occurrences.
Display the main string, the substring, and the number of occurrences as output.
Deallocate the memory used by the dynamic strings.
Solution
#include
#include
#include
int countOccurrences(char* mainString, char* substring) {
int count = 0;
int mainLength = strlen(mainString);
int subLength = strlen(substring);
if (mainLength < subLength) {
return count;
}
for (int i = 0; i <= mainLength - subLength; i++) {
if (strncmp(mainString + i, substring, subLength) == 0) {
count++;
}
}
return count;
}
int main() {
char* mainString = NULL;
char* substring = NULL;
printf("Enter the main string: ");
scanf("%ms", &mainString);
printf("Enter the substring: ");
scanf("%ms", &substring);
int occurrences = countOccurrences(mainString, substring);
printf("Main string: %s\n", mainString);
printf("Substring: %s\n", substring);
printf("Number of occurrences: %d\n", occurrences);
// Deallocate the memory used by the dynamic strings
free(mainString);
free(substring);
return 0;
}
Explanation
The program defines a function countOccurrences() that takes two dynamic strings (mainString and substring) as arguments and returns the number of occurrences of the substring within the main string. In the countOccurrences() function, the lengths of the main string and the substring are calculated using strlen(). If the length of the main string is less than the length of the substring, the function returns 0 as there can be no occurrences. The function then iterates through the main string and checks for occurrences of the substring using strncmp(). In the main function, the user is prompted to enter the main string and the substring using scanf("%ms", &mainString) and scanf("%ms", &substring), respectively. The %ms format specifier allocates memory dynamically for the input strings. The main string and the substring are passed to the countOccurrences() function to find and count occurrences. The main string, the substring, and the number of occurrences are displayed using printf(). Finally, the memory used by the dynamic strings is deallocated using free() to avoid memory leaks.