The program includes the following main function: int main() { char str1[20], str2[80]; scanf("%s%s", str1, str2); printf("%d\n", occurrence1(str1, str2)); printf("%d\n", occurrence2(str1, str2)); return 0; } The program also includes two occurrence functions: occurrence1 and occurrence2. int occurrence#(char *sub, char *str)/* # is 1 or 2*/ is the function that finds number of occurrences of sub in str. For example, a)occurrence1("ab","abc") returns 1; b)occurrence1("ab","bac") returns 0; c)occurrence1("aba","ababa") returns 2; Occurrence1 is a recursive function, occurrence2 is non-recursive function.
时间: 2024-04-12 13:29:11 浏览: 126
Based on the given requirements, here's the implementation of the two occurrence functions (`occurrence1` and `occurrence2`) in C:
```c
#include <stdio.h>
#include <string.h>
int occurrence1(char *sub, char *str) {
if (*str == '\0')
return 0;
else if (strncmp(sub, str, strlen(sub)) == 0)
return 1 + occurrence1(sub, str + strlen(sub));
else
return occurrence1(sub, str + 1);
}
int occurrence2(char *sub, char *str) {
int count = 0;
int sub_len = strlen(sub);
int str_len = strlen(str);
for (int i = 0; i <= str_len - sub_len; i++) {
if (strncmp(sub, str + i, sub_len) == 0)
count++;
}
return count;
}
int main() {
char str1[20], str2[80];
scanf("%s%s", str1, str2);
printf("%d\n", occurrence1(str1, str2));
printf("%d\n", occurrence2(str1, str2));
return 0;
}
```
In this program, the `occurrence1` function uses recursion to find the number of occurrences of `sub` in `str`. It checks if the current substring of `str` matches the `sub` string. If there is a match, it increases the count by 1 and recursively calls `occurrence1` on the remaining part of `str`. If there is no match, it recursively calls `occurrence1` on `str` excluding the first character.
The `occurrence2` function is a non-recursive alternative that uses a loop to iterate over `str` and compare substrings of length `sub_len` with `sub`. It increases the count whenever a match is found.
The main function reads two strings from input using `scanf` and then calls `occurrence1` and `occurrence2` functions respectively to find the occurrences of `str1` in `str2`, printing the results using `printf`.
Please note that the program assumes the input strings (`str1` and `str2`) are null-terminated strings.
阅读全文