c语言编写程序查找一个字符串在另一个字符串中出现的次数,使用递归
时间: 2023-12-30 15:02:50 浏览: 35
好的,以下是一个使用递归来查找一个字符串在另一个字符串中出现次数的示例程序,使用C语言编写:
```c
#include <stdio.h>
int count_occurrences(char *text, char *pattern) {
if (*text == '\0')
return 0;
else if (strncmp(text, pattern, strlen(pattern)) == 0)
return 1 + count_occurrences(text + strlen(pattern), pattern);
else
return count_occurrences(text + 1, pattern);
}
int main() {
char text[] = "abababa";
char pattern[] = "aba";
printf("字符串 '%s' 在 '%s' 中出现的次数为: %d\n", pattern, text, count_occurrences(text, pattern));
return 0;
}
```
在这个程序中,`count_occurrences` 函数使用递归来查找字符串 `pattern` 在字符串 `text` 中出现的次数。它首先检查 `text` 是否已经到达字符串结尾,如果是则返回 0。然后,它使用 `strncmp` 函数来比较 `text` 和 `pattern` 的前缀,并检查它们是否相等。如果相等,则返回 1 加上递归调用 `count_occurrences` 函数在剩余部分中查找出现次数。如果不相等,则递归调用 `count_occurrences` 函数在 `text` 的下一个字符开始的位置继续查找出现次数。
在上述示例中,字符串 "aba" 在字符串 "abababa" 中出现的次数为 2。